Al.s
Al.s

Reputation: 310

Comparison of innerHTML with JQuery

I am trying to change <p> background according to its contact (innerHTML) but I cant get it to work.

<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("button").click(function(){
        if ($("p").innerHTML === "just a test"){
            $("p").css("background","yellow");
        }
    });
});
</script>
</head>
<body>

<p>just a test number1</p>
<p>just a test number2</p>
<p>just a test</p>

<button>Execute</button>

</body> 

I expected only the last <p> background to change but nothing happens, why is that?

Upvotes: 0

Views: 174

Answers (2)

Beri
Beri

Reputation: 11610

InnerHtml is a JavaScript property, it does not belong in jQuery.

You need to change this:

 $("p").innerHTML === "just a test"

to this:

 $("p").html() === "just a test"

Secondly selector p is quite big, expecially that you are not calling it form any element, but in global scope. I would advise to use some sort of class or id, if it is possiblem.

Thirdly I would go with such fix to your algoritm:

$("p").each(function(){
   var el = $(this);
   if(el.htlm() === 'just a test'){ // could change for regexp (bevare of white characters)
      el.css("background","yellow")
   }
});

This way for every p element that inner html is 'just a test' you will change background color.

Upvotes: 0

Quentin
Quentin

Reputation: 943579

There is no innerHTML property on a jQuery object, so $("p").innerHTML === "just a test" will always be false.

You could use .html() instead, but that would always return the data from first element that matched the selector, so it would still always be false.

Even if that wasn't the case, $("p").css("background","yellow"); would set the background of all the paragraphs.


You need to loop over all the elements and test each one in turn.

$(document).ready(function() {
  $("button").click(function() {
    $("p").each(function(index, paragraph) {
      var $p = $(paragraph);
      if ($p.html() === "just a test") {
        $p.css("background", "yellow");
      }
    });
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>just a test number1</p>
<p>just a test number2</p>
<p>just a test</p>

<button>Execute</button>

Upvotes: 2

Related Questions