0

I was wondering how I can use the data-* attribute of a parent div to set a placeholder in a child div.

I am modifying a form and am somewhat restricted in editing the code of the div itself so I need to use JavaScript to add the necessary attributes.

Some info:

  • The parent and child divs do not have a unique ID or class which makes a straightforward approach like getElementBy...().placeholder="blahblah"; not possible
  • The format of the heirarchy and respective classes and IDs are shared globally across all fields in the form. They all have a parent div (class defines width of box), and 3 child divs within ("aaa - label", "bbb - editor", "ccc - validation")
  • The parent div does have a data-field I can possibly make use of since the placeholder necessary depends on the type of input (DOB, SSN, etc.)

Is there a way I can get the data-* name and assign a placeholder to its child? I know you can grab the data-* attribute itself using getAttribute('data-field'); but how to specify the name value attached to it?

How do I specifically target data-field="SSN" and then assign a placeholder to class="bbb" in the child div contained within?

Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
  • Is this what you look for?: http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery – Asons Oct 24 '16 at 20:32

2 Answers2

0

Is this what you are describing in your last question?

$('*[data-field="SSN"]').children().find('.bbb');

"Find any node with data-field equal to SSN, then for its children, find a node classed bbb" ?

0

So the markup would look like this then?

<div data-field="SSN">
    <label for="text" class="aaa">label</label>
    <input type="text" class="bbb">
    <span class="ccc">validation</span>
</div>

If so then you may want to use this :

$('div[data-field="SSN"]').children('.bbb').prop('placeholder', 'some_text_here');

Fiddle: here

four
  • 564
  • 4
  • 6