Samson
Samson

Reputation: 352

How to add an attribute to an input box that is present inside of a div

I have a div with a class, inside of a div where I have one input box. I need to add the attribute list='emp' to the input box.

<div class="divInput">
  <input type="text">
</div>

$(".divInput").prop("list","emp");

Here I am not able to add the attribute.

Upvotes: 1

Views: 1293

Answers (2)

gavgrif
gavgrif

Reputation: 15499

You don't need jQuery for this - simply target the input with .document.querySelector() and and set the attribute with straight JS (.setAttribute()..).

Note that I added a placeholder attribute to demonstrate the success of this method.

let input = document.querySelector('.divInput input');
input.setAttribute("list","emp"); // inpect the input to find the attribute
input.setAttribute("placeholder","Example text"); // added to demonstrate the attribute has been set
<div class="divInput">
  <input type="text">
</div>

Upvotes: 1

jolsalazar
jolsalazar

Reputation: 418

This code adds an attribute to your text box, inside your container.

$(document).ready(function(){
  $(".divInput").children().attr("list", "emp");
  $(".divInput").children().prop("value","example");
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="divInput">
  <input type="text">
</div>

Upvotes: 2

Related Questions