Hide Divs with similar ID

Asked

Viewed 259 times

7

I have several tags div with the similar id, they all start with cn-, example:

<div id="cn-name">...</div>
<div id="cn-email">...</div>
<div id="cn-pass">...</div>

How can I interact with all of them without having to specify one by one? Would there be any way to do this at the beginning of it? For example:

/* no css */
#cn-* {
  display:none;
}

/* no javascript/jquery */
$('#cn-*').hide();
  • 1

    Couldn’t there be a class for all these same fields? Example: CNs, it would be easier to manipulate with just $('.CNs').hide()

  • I think I would give @Marcelodeandrade, but I would have to refactor a lot. Anyway would be a great way out, thanks.

1 answer

9


See these two options

CSS:

div[id^='cn-'] {
  display:none;
}

or jQuery:

$('div[id^="cn-"]').hide();

This will allow you to select all elements that contain cn- at the beginning of the ID.

Taken from the Soen: css-selector-id-contains-part-of-text

Selectors:

  • [atributo^=valor]: selects all elements that the atributo begin with valor
  • [atributo$=valor]: selects all elements that the atributo end with valor
  • [atributo*=valor]: selects all elements that the atributo contain valor

Source: css selectors

  • 1

    Excellent! That’s right, thank you @Pedrocamarajunior

  • 2

    Pedro, the selector for #cn-* (idthat begin with cd-) is [id^='cn-'], uses the *= can return elements that do not start with cn, but has cn in name, as #bt-cnida

  • @Tobymosque corrected, thanks for the touch!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.