Select an id that ends with something inside a particular div

<div id="mydiv">
    <div id="abcdiv">yes div</div>
    <div id="defdiv">yes div</div>
    <div id="ijkdiv">yes div</div>
    <div id="notthisone">No div</div>
</div>
<div id="xyzdiv">No div</div>

I need to select only the divs that ends with the id "div" and also only those that are inside <div id="mydiv">

In this case, my output should be only the following divs

<div id="abcdiv">yes div</div>
<div id="defdiv">yes div</div>
<div id="ijkdiv">yes div</div>

and not

<div id="notthisone">No div</div> and <div id="xyzdiv">No div</div>

Answers


Try to use attribute ends with selector at this context,

var elem = $("#mydiv div[id$='div']");
DEMO

And that above selector is a valid css selector too. You can use it in css also.

#mydiv div[id$='div'] {
 color : red;
}

But note that this selector will use regex under the hood. That may drain the performance when you are running this selector in a dom with 100+ elements. So the better approach would be using a class to distinguish the required element from the others. Like,

<div id="mydiv">
    <div id="abcdiv" class="yes">yes div</div>
    <div id="defdiv" class="yes">yes div</div>
    <div id="ijkdiv" class="yes">yes div</div>
    <div id="notthisone">No div</div>
</div>

And the selector will be like,

#mydiv div.yes {
 color :red;
}

You can use [attr$=value] attribute selector

Represents an element with an attribute name of attr and whose value is suffixed by "value".

#mydiv div[id$="div"] {
  background: lightblue;
}
<div id="mydiv">
  <div id="abcdiv">yes div</div>
  <div id="defdiv">yes div</div>
  <div id="ijkdiv">yes div</div>
  <div id="notthisone">No div</div>
</div>
<div id="xyzdiv">No div</div>

div#mydiv div[id$=div] matches all of your criteria :

  • The element must be inside a <div> with id mydiv
  • The element must be a <div> itself
  • The id of the element must end with div

Demo

div#mydiv div[id$=div] {
    background: green;
}
<div id="mydiv">
    <div id="abcdiv">yes div</div>
    <div id="defdiv">yes div</div>
    <div id="ijkdiv">yes div</div>
    <div id="notthisone">No div</div>
    <section id="notadiv">Not a div</section>
    <section id="notadiv">
       Also not a div
       <div id="inceptiondiv">inception</div>
    </section>
</div>
<div id="xyzdiv">No div</div>

Need Your Help

How to use tempfile.NamedTemporaryFile()?

python temporary-files

I'm working on a Python script that needs to create about 50 distinct temporary files, which are all appended frequently during the course of the script and merged at the end. I'm sure that the tem...