How could I replace multiple div without set few functions onclick? - javascript

I'm using vanilla JS for some reasons and trying to replace div content while click on li.
I'm tried to replace by function(target, source) but target is always = id.
So I'm clone my function and onclick li insert 2 functions + params.
<body>
<li onClick="replaceContentInContainer('target', 'replace_target_div2'); replaceContentInContainerTwo('targetTwo', 'replace_target_div2_02')">View Div 2</li>
<li onClick="replaceContentInContainer('target', 'replace_target_div3'); replaceContentInContainerTwo('targetTwo', 'replace_target_div3_02')">View Div 3</li>
<div>
<span id="target">div1</span>
</div>
<div style="display:none">
<span id="replace_target_div2">div2</span>
</div>
<div style="display:none">
<span id="replace_target_div3">div3</span>
</div>
<div>
<span id="targetTwo">div1</span>
</div>
<div style="display:none">
<span id="replace_target_div2_02">div2 02</span>
</div>
<div style="display:none">
<span id="replace_target_div3_02">div3 03</span>
</div>
</body>
<script>
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
function replaceContentInContainerTwo(targetTwo, sourceTwo) {
document.getElementById(targetTwo).innerHTML = document.getElementById(sourceTwo).innerHTML;
}
</script>
I would like to have elegant way to do so.

I think what you mean is that you want to keep your HTML clean.
You could use a click eventhandler on all li within a certain ul.
HTML
<ul id="theList">
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
JS add Click event handler
// Get all list items in ul with id 'theList'
var listItems = document.querySelectorAll('#theList li');
// Add a click event handler on each list item
for (i = 0; i < listItems.length; i++) {
listItems[i].addEventListener("click", function(){
console.log(this) // This is your target html
});
}
For the last step I'm not sure what you want. I don't know how your source is chosen. I will edit if you explain it more.

You can user this code:
<body>
<li onClick="replaceContentInContainer('target', 'div2');">View Div 2</li>
<li onClick="replaceContentInContainer('target', 'div3')">View Div 3</li>
<div>
<span class="target">div1</span>
</div>
<div>
<span class="target">div1</span>
</div>
</body>
<script>
function replaceContentInContainer(div, text) {
var ids = document.getElementsByClassName(div);
for (var i = 0; i < ids.length; i++) {
ids[i].innerText = text;
}
}
</script>

Related

Get element after a specific sibling element by the sibling's text

I have the following html code:
<div class="account-type">
<h3>Assets</h3>
<ul> ...lots of data in here... </ul>
<div class="account-type">
<h3>Liabilities</h3>
<ul> .... lots of elements in here... </ul>
How do I isolate the div tag with the class of "account-type" that is the direct parent of the h3 tag with the text "Liabilities"? I need to isolate it and then loop through all of the elements in it's ul tags.
Assuming <ul> should come after <h3>, you can use this combination:
:contains
:next
children
function getItemByTitle( title ){
return $(`h3:contains("${title}")`).next('ul').children()
}
var listItems = getItemByTitle("Liabilities")
console.log(listItems.length)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="account-type">
<h3>Assets</h3>
<ul></ul>
</div>
<div class="account-type">
<h3>Liabilities</h3>
<ul>
<li>1</li>
<li>2</li>
</ul>
</div>
There is no text match in DOM so need to select all the elements, look to see if the text matches. If it does select the parent.
const h3 = Array.from(document.querySelectorAll(".account-type > h3")).find(elem => elem.textContent.trim() === 'Liabilities');
console.log(h3)
const div = h3.closest(".account-type");
console.log(div);
const lis = div.querySelectorAll("ul li");
console.log(lis.length);
// or
console.log(h3.nextElementSibling.children)
<div class="account-type">
<h3>Assets</h3>
<ul></ul>
</div>
<div class="account-type">
<h3>Liabilities</h3>
<ul>
<li>a</li>
<li>b</li>
</ul>
</div>

how to get text inside a li element on click in pure javascript

The folliwing code is working ONLY with the getElementById method, but i need it to works even in the case there is not an ID on element.
My HTML is:
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>
My JS is:
<script>
var el = document.getElementById("pid");
el.onclick = function what_to_do(){
var theText = this.innerHTML;
alert(theText);
</script>
So i need to get the text in the deepest nested LI element that has no ID when the user clicks over it.
usually with jquery i can make $("#container ul li ul li").on("click, ...
but i am trying to work with pure javascript (vanilla js).
Is there anyone else that can help me?
Thanks in advance
You can use document.querySelectorAll().
Note: You can't just set event to the document.querySelectorAll() like jQuery you need to loops through whole array
const items = document.querySelectorAll('li > ul > li');
items.forEach(item => {
item.addEventListener('click',(e)=>{
console.log(e.target.textContent);
}
)
})
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>
use document.querySelector
var el = document.querySelector("#container > .menu > li > .submenu > li");
el.onclick = function what_to_do(){
var theText = this.innerHTML;
alert(theText);
}
<div id="container">
<ul class="menu">
<li>
<ul class="submenu">
<li>text i have to get</li>
</ul>
</li>
</ul>
</div>

Chaining jquery append

I'm trying to figure out how I can chain multiple append into my markup. Basically after appending an element, I would like the next element to append it to the first appended element. I hope what I'm saying makes sense.
If you take a look at my code, I just appended the element <ul class="menu" /> into the element #footer .research-centers-menu .research.
Then on the next code I'm trying to insert/append the variable centers to the <ul class="menu" />
The current output right now doesn't insert the element but places it outside instead. Apologies for my bad english and explanation
var researchCenters = $('a[href$="/items"]').next().clone(),
centersList = $('li', researchCenters),
centers = centersList.slice(0);
var research = $('#footer .research-centers-menu .research').append('<ul class="menu" />');
$(research).append(centers);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<ul>
<li>item one</li>
<li>item two</li>
</ul>
</li>
</ul>
<div id="footer">
this is a footer
<div class="research-centers-menu">
<div class="research">
</div>
</div>
</div>
The cause of your appending issue is because append() returns the original element, not the appended element.
To make your code work you could invert the logic so that you create the new ul, then use appendTo(). This will retain the reference required to append the li. Try this:
var researchCenters = $('a[href$="/items"]').next().clone(),
centersList = $('li', researchCenters);
var $research = $('#footer .research-centers-menu .research');
var $ul = $('<ul class="menu" />').appendTo($research);
$ul.append(centersList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>
<ul>
<li>item one</li>
<li>item two</li>
</ul>
</li>
</ul>
<div id="footer">
this is a footer
<div class="research-centers-menu">
<div class="research"></div>
</div>
</div>
try to append like this.
var researchCenters = $('a[href$="/items"]').next().clone(),
centersList = $('li', researchCenters),
centers = centersList.slice(0);
var research = $('#footer .research-centers-menu .research')
var ul =$('<ul class="menu" />').append(centers);
research.append(ul);

How to loop a button

I am not sure if loop is the right term, but I have a products page that is working perfectly. I want to be able to have an " Add product option button" that when the admin clicks on it, it toggles down and another "Add products option button" replaces the one i just opened. So the number of products options is unlimited, the user will be able to add as many products as they like.
<!--Restaurant toggle-->
<a id="restt" class ="header"href="#" onclick="toggleVisibility('Rest');">
<h3 id="open">Your Restaurants</h3>
</a>
<div id="Rest" class="Rest_new" style="display: none;"><div>
<ul class="tabs1">
<!--
<li id="order" class="rred">
restaurant
</li>
-->
<li id="order_open" class="rgreen">
New restaurant
</li>
</ul>
</div>
</div>
<!-- add element-->
<script>
$(document).on('click', 'li#order_open', function() {
$(this).before('<li>New restaurant</li>');
// add to localsorage?
window.onload = function() {}
var order_open = $('div#Rest').html();
localStorage.setItem('div#Rest', order_open);
});
</script>
I am using the following code at the moment. It creates unlimited options however, i can not open the options, i cannot make it toggle and it disappears on page refresh. Is there a better way to do this.
You question is javascript. You could use
$('container').append('html content');
See an example:
$(document).ready(function(){
$("#btn1").click(function(){
$("p").append(" <b>Appended text</b>.");
});
$("#btn2").click(function(){
$("ol").append("<li>Appended item</li>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<ol>
<li>List item 1</li>
<li>List item 2</li>
<li>List item 3</li>
</ol>
<button id="btn1">Append text</button>
<button id="btn2">Append list items</button>
See more
http://www.w3schools.com/jquery/jquery_dom_add.asp
To create additional restaurants, you can use jQuery's append function to add the link. Then use localstorage to store and retrieve the number of links created.
HTML
<h3 id="open">Your Restaurants</h3>
<div class="Rest_new" id="rest">
<div>
<ul class="tabs1" id="optionContainer">
</ul>
</div>
JavaScrtipt
var options = parseInt(localStorage.getItem('numberOfOptions'));
if(isNaN(options)) { options = 0; }
function addOption(n) {
$('#optionContainer').append('<li class="rgreen" id="order_open'+n+'">New restaurant '+n+'</li>');
}
$(document).ready(function(){
for(var i = 0; i < options; i++) {
addOption(i);
}
$('#open').on('click',function() {
addOption(options);
options++;
localStorage.setItem('numberOfOptions',parseInt(options));
})
});
You can see it working here: https://jsfiddle.net/igor_9000/pm4Lv44t/1/
Hope that helps!

Trigger event with same ID elements

I have a menu list that refer to different projects.
Each list item shares its "ID" with a project showcased in a gallery.
<div class="menu">
<ul>
<li id="id1">project 1</li>
</ul>
</div>
<div class="gallery">
<div class="proc id="id1">project 1</div>
</div>
I'd like a jQuery function that :
When a list item from the menu is clicked, gets the project with the same id to do something.
I really don't know where to start from and I'm stuck at that :
<script>
$( "li#id1").click(function() {
$( ".project#id1" ).show();
});
</script>
Many thanks
As the comments said the IDs must be unique and you have missing quote.
You can use data attributes to handle your logic or combination of ids and data attributes.
Try something like this:
HTML
<div class="menu">
<ul>
<li data-project-id="first-project-id">project 1</li>
...
</ul>
</div>
<div class="gallery">
<div class="proc" data-project-id="first-project-id">project 1</div>
</div>
JavaScript
$('.menu li').click(function(){
var targetId = $(this).attr('data-project-id');
$('.proc[data-project-id="' + targetId + '"]').show();
});
The click event is attached to every li item in the element with class .menu.
On click event we extract the data-project-id attribute from the clicked element, find the project elemenet from gallery and show it.
JSFiddle Demo
you can use normal id also (as selector)
HTML
<div class="menu">
<ul>
<li id="first-project-id">project 1</li>
...
</ul>
</div>
<div class="gallery">
<div class="proc" id="first-project-id">project 1</div>
</div>
jQuery
$('.menu li').click(function(){
var targetId = $(this).attr('id');
$('.proc[id="' + targetId + '"]').toggle();
});

Categories

Resources