Insert Html tag inside a DIV

时间:2016-04-15 14:47:26

标签: jquery html css

How can I insert a html tag like <p> to enclose the "Search" text.

<button id="ihf-quicksearch-submit2" class="btn btn-lg btn-block btn-primary btn-form-submit ihf-main-search-form-submit" type="submit"> Search </button>

Because I want to hide that "Search" text when the page width is equal =< 900. So that it will be change to a magnifying glass glyph icon.

I have tried jQuery.

<script type="text/javascript">
jQuery(document).ready(function(){ 
var windowsize = jQuery(window).width();

jQuery(window).resize(function() {
  windowsize = jQuery(window).width();
  if (windowsize < 900) {
    jQuery('#ihf-quicksearch-submit2').html('<i class="glyphicon glyphicon-search fa fa-search"></i>');
  } if (windowsize >900) {
    jQuery('#ihf-quicksearch-submit2').html(' Search ');
}
});
});
</script>

jQuery worked for changing the "Search" to magnifying glass icon. BUT when page is still loading it still shows the "Search" text. And it doesn't look good on mobile version.

So I want to have a "HTML tag" before the "Search" so I can "display:none;" it from CSS using @media CSS.

NOTE: I can't insert <p> manually cause I cant locate the code from the plugin that I am using.

Any thoughts?

4 个答案:

答案 0 :(得分:2)

非常简单 - 按ID获取按钮的HTML,然后将其修改为字符串,并将其存储回按钮的HTML中。

var innerHTML = $('#ihf-quicksearch-submit2').html();
innerHTML = '<p>' + innerHTML + '</p>';
$('#ihf-quicksearch-submit2').html(innerHTML);

Demo Here

答案 1 :(得分:1)

You could just stick them both in there and hide them based on a media query:

<script   src="http://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

<button id="ihf-quicksearch-submit2" class="btn btn-lg btn-block btn-primary btn-form-submit ihf-main-search-form-submit" type="submit"> Search </button>

<style>
@media screen and (max-width:900px) {
   .search-text {
  display: none;
   }
   #ihf-quicksearch-submit2 {
  opacity: 0;
   }
}
@media screen and (min-width:900px) {
   .search-icon {
  display: none;
   }
}
</style>

<script>
$("#ihf-quicksearch-submit2").html('<i class="glyphicon glyphicon-search fa fa-search search-icon"></i><span class="search-text">Search</span>').css( "opacity", "1" );
</script>

答案 2 :(得分:0)

所以这是我的问题的答案。万一有人在那里遇到与我相同的问题。我将“Tricky12”和“Jeff Puckett II”的答案结合起来 - 给予他们信用。

#--    [[  fruit -> id  ]/[   id -> fruit  ]]*
:apple ((veg:one|veg:two)/^(veg:one|veg:two))* ?other .

答案 3 :(得分:0)

如果该div还有其他子级,并且您不需要全部擦除,则可以在javascipt中使用此方法

JavaScript

var CodeInsideDiv = document.getElementById("samplediv")
var injection = "<p>sample text</p>"
CodeInsideDiv.innerHTML = injection + CodeInsideDiv.innerHTML

在HTML中会发生

<div id="samplediv">

<p>sample text<p> #<<<--Magic inserted this  here#

<p>SAMPLE TEXT</p>
<div id="nested-div">....</div>   
</div>