Display only the first of <h1> that has a different name

Headers are dynamically obtained. The structure is as follows:

<h1>HEADING CONTENT 1</h1>
some content
<h1>HEADING CONTENT 1</h1>
some content
<h1>HEADING CONTENT 1</h1>
some content
<h1>HEADING CONTENT 2</h1>
some content
<h1>HEADING CONTENT 2</h1>
some content

I need to display only the first instance of each header. How to do it?

EDIT: Sorry, I'm on a different PC right now. As soon as I can.

+4
source share
3 answers

If your headers are actually siblings, as in your structure, you can use the sibling common selector / combinator ~and thus display: noneall duplicate headers

h1 ~ h1, 
h2 ~ h2 {
   display: none;
}

Sample code: http://codepen.io/anon/pen/Evuhr/


After update :

<h1>, , , javascript/jQuery

$(function() {
  var title = ""
  $('h1').each(function() {
     if ($(this).text() !== title) {
        title = $(this).text();
     } 
     else {
       $(this).hide();  
     }    
  });  
});

: http://codepen.io/anon/pen/FBltb

+7

, , CSS .

h1, h2 {
    display:none;
}

h1:first-of-type, h2:first-of-type {
    display: inline-block;
}
0

Update

If you use the title tag <h1>and want to show first based on the inner text, you can use :containsand .first()to get the desired result:

Check out this script

CSS hide all h1s first

h1{
    display:none;
} 

JQuery

$("h1").each(function(){
    $("h1:contains('"+$(this).text()+"')").first().css('display','block');
});

jQuery with the best ops / sec:

var $h1s = $("h1");
$h1s.each(function (i) {
    if ($(this).data('validated')) {
        return;
    }
    $h1s.filter(":contains('" + $(this).text() + "')").data('validated', true).first().show();
});

Fiddle

0
source

Source: https://habr.com/ru/post/1534824/


All Articles