Distinguishing between two same HTML ID elements u

2020-07-24 03:40发布

问题:

I know that is a bad practice to have more than HTML elements having same ID. However such is my situation where I need to specifically modify either of them.

I researched around and found about Jquery method 'document.getElementByID' that returns with the first similar element and lets you change it using css. Using that I wrote the code below but it doesn't work.

$(document.getElementById('it_trending-3')).css({"display":"none"});

I have added this code in my wordpress theme using the CSS-JS-PHP wordpress plugin, created a shortcut from the same and then added the shortcode. Can someone please guide me what and where I went wrong?

Also feel free to suggest a different function that would maybe let me specifically point to each of the same ID elements using maybe indexes. Thanks!

回答1:

Keep a class to the divs you want to change:

<div>
    <span id="a" class="test">1</span>
    <span id="b" class="test">2</span>
    <span>3</span>
</div>

The Jquery would go like this:

$(function() {
    var w = $("div");
    console.log($('#a').length);
    console.log($('body #a').length);
    console.log($('#a', w).length);
});

$(".test").first().css({"color":"orange"});
//or
$(".test:first").css({"color":"orange"});

But if you want to select any specific element with the class via an index of sorts, then you would need to do it like this:

var x = $(".test");
$(x[1]).css({"color":"orange"});


回答2:

You can achieve this in 2 ways.

Based on element's hierarchy or based on class attribute / custom data attribute to the element.

In the below example we have 3 span elements with the same id and we have to apply 3 colors to each of those span elements.

HTML

<div>
  <span id="it_trending-3">
    Applying css to same Id with hierarchy  (span in 1st div)
  </span>
</div>
<div>
<span id="it_trending-3">
Applying css to same Id with hierarchy (span in 2nd div)
</span>
</div>

<br /><br /><br />
<span id="it_trending-3" class="testcls">
  Applying css to same Id with class
</span>
  1. Applying css using js / jquery based on element hierarchy

JQuery

(function($){
  $("div:last #it_trending-3").css("color", "red");
  $("div:first #it_trending-3").css("color", "green");
})(jQuery);
  1. Based on class attribute / custom data attribute to the element.

JQuery

(function($){
  $("#it_trending-3.testcls").css("color", "blue");
})(jQuery);

JS Fiddle Demo