abrahamlinkedin abrahamlinkedin - 2 months ago 7
Javascript Question

click function for each designated class item

I have a function that is supposed to correspond with each

li
. With plain JavaScript, I would like to know how to replace the HTML on
listitem
to whatever the user has input.

I would like only the function that is clicked to run, and only for the appropriate row (in this case, li).



function day(el){
var listitem = document.getElementsByClassName('listitem');
var changebox = document.getElementsByClassName('changebox');

listitem[el].innerHTML = changebox[el].value;
}

ul li {list-style-type: none;}
.changebox {width: 40px;}

<ul>
<li>
<span class="listitem">Item 1</span>
<input type="text" class="changebox"/>
<button onclick="day(this)">Edit</button>
</li>

<li>
<span class="listitem">Item 1</span>
<input type="text" class="changebox"/>
<button onclick="day(this)">Edit</button>
</li>

</ul>




Answer

This replaces the entire line item, I didn't know if you wanted the changebox to stay or not and used the slightly less verbose queryselector instead of getElementByClassName.

function day(el){
var parent = el.parentNode;
var changebox = parent.querySelector('.changebox')
var listitem = parent.querySelector('.listitem')

listitem.innerHTML = "Item " + changebox.value;
}
ul li {list-style-type: none;}
.changebox {width: 40px;}
<ul>
<li>
<span class="listitem">Item 1</span>
<input type="text" class="changebox"/>
<button onclick="day(this)">Edit</button>
</li>

<li>
<span class="listitem">Item 1</span>
<input type="text" class="changebox"/>
<button onclick="day(this)">Edit</button>
</li>

</ul>