How to set element id based on innerHTML using javascript - javascript

I want to add id for all the heading tag from dynamic content. The id should be based on innertext of the same element(this is to create the link for particular section).
Ex:
if heading tag have <h1 class="title_tag">Key Programming Language</h1>,
the output should be <h1 id="key-programming-language" class="title_tag">Key Programming Language</h1>
i am not sure how get innerHTML value into id. Please suggest me the solution using any javascript(or)jquery(or)PHP

const convertToKebabCase = (string) => {
return string.replace(/\s+/g, '-').toLowerCase();
}
const h1 = document.querySelectorAll("h1");
h1.forEach(el=>{
const kebabCaseText = convertToKebabCase(el.innerText);
el.id = kebabCaseText;
})
<h1 class="title_tag">Key Programming Language</h1>

This what you're trying to do?
$("h1").each(function(){
var newId = $(this).text().replace(" ", "-");
//console.log(newId);
$(this).attr('id', newId);
});

or pure Javascript:
var elements = document.getElementsByTagName("1");
for (i = 0; i < elements.length; i++) {
elemelements[i].id = elements[i].innerHTML;
}

Related

Split multiple class with same name using loop

I have a multiple tag in my webpage with the same class called price. Each tag is of that form
<p class="price">Price: 45$</p>
<p class="price">Price: 32$</p>
What I need at the end is to separate the price text in a span and the price in another so that it will be like that
<p class="price"><span class='h1'>Price:</span> <span class="h2">45$</span></p>
This is what I do until now but problem is that the span is not a tag but is insert as a simple string
let price = $(".price");
for (let i = 0; i < price.length; i++) {
let priceTitle = price[i].innerText.split(":")[0];
let priceToPay = price[i].innerText.split(":")[1];
price[i].innerText = ''; //Delete content of price
$(".price")[i].append("<span class='h1'>"+ priceTitle+"</span> <span class='h2'>"+ priceToPay +"</span>");
}
}
Can you help me fix this issue and perhaps optimize the code I already do.
You've just a few syntax errors e.g. you've set priceToPay then used price_toPay in your final line of code. Also jQuery.append() method is setting your content as textContent and not HTML but just use innerHTML instead. I've added a button for you to click so you can see the before and after effects. See below
window.onload = () => {
document.getElementById('mybutton').addEventListener('click', doFormat);
}
function doFormat() {
let price = $(".price");
for (let i = 0; i < price.length; i++) {
const priceTextContentArray = price[i].innerText.split(":");
let priceTitle = priceTextContentArray[0];
let priceToPay = priceTextContentArray[1];
price[i].innerHTML =
"<span class='h1'>" +
priceTitle +
"</span> <span class='h2'>" +
priceToPay +
"</span>";
}
}
.h1 {
background-color: skyblue;
}
.h2 {
background-color: coral;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer" defer></script>
<button id='mybutton'>Format</button><br>
<p class="price">Price: 45$</p>
<p class="price">Price: 32$</p>
If you want to do it "the jQuery way", to build elements from strings you must use the $ constructor:
replace:
price[i].innerText = ''; //Delete content of price
$(".price")[i].append("<span class='h1'>"+ priceTitle+"</span> <span class='h2'>"+ priceToPay +"</span>");
by:
$(price[i]).html('').append( $("<span class='h1'>"+ priceTitle +"</span> <span class='h2'>"+ priceToPay +"</span>") );
As you see in jQuery you can also chain the calls, and use the .html() or .text() dedicated functions. html is more suitable here as you want to delete all inside your element, not just the text part
Notice that I also corrected your $(".price")[i] to $(price[i]), it is safer to use the var you loop on instead of doing a new jQuery selection and assume it will have the same index as in your loop

How to display elements data stored in a javascript array as list elements in the DOM

I am a newbie at web development. I am trying to display data that is being stored in javascript array, inside an unordered list as list elements.
I have tried looping through the elements in the array and display them one at a time using for loops but its not working
let linksArray = [] // array to store link leads while browsing
let inputEl = document.getElementById("input-el") // to get a hold on the input element from the dom
let displayEl = document.getElementById("display_link-el")
//function to save links inputs into linksArray
function save(params) {
linksArray.push(inputEl.value)
console.log(linksArray);
localStorage.setItem("mylinks", JSON.stringify(linksArray))
inputEl.value = ""
displayEl.textContent = linksArray
}
//function to conver linksArray to a list element in the DOM
function convetToListli(linksArray) {
for (let i = 0; i < linksArray.length; i++) {
let links = "<li>"
linksArray[i]
" </li>"
}
}
<input id="input-el" title="lead" placeholder="input weblink" type="text">
<button id="input-btn" onclick="save()">SAVE </button>
<button id="del-btn" ondblclick="delLeads()">DELETE</button>
<div>
<div>
<ul id="display_link-el"></ul>
</div>
<div>
<ul id="log_link-el"></ul>
</div>
</div>
I have added small correction to your script
function save(params) {
linksArray.push(inputEl.value)
console.log(linksArray);
inputEl.value=""
displayEl.innerHTML = convetToListli(linksArray)
}
//function to conver linksArray to a list element in the DOM
function convetToListli(linksArray) {
var links = ""
for (let i = 0; i < linksArray.length; i++) {
links= links + "<li>"+linksArray[i]+" </li>"
}
return links
}
This is just for example purchase
NOTE: Make sure to filter the input field while using innerHTML because it will leads to XSS
You should learn basic DOM manipulations. Here's one possible solution for your question
const list = document.querySelector('.list');
const links = ['link 1', 'link 2', 'link 3'];
links.forEach(link => {
let item = document.createElement('li');
item.textContent = link;
list.appendChild(item)
})
<ul class="list"></ul>

Adding ID based on innerHTML to all elements in class

I need to write a code to add IDs to all element in one class. The IDs have to be based on innerText.
Elements look like that:
<lable class="sf-label-radio">Name1<span>Some Other Text that I do not need</span><label>
<lable class="sf-label-radio">Name2<span>Some Other Text that I do not need</span><label>
etc.
Here is my code:
<script>
addIDtoGI();
function addIDtoGI() {
let searchButtons = document.getElementsByClassName('sf-label-radio');
for(i = 0; i < searchButtons.length; i++) {
x = searchButtons[i].innerHTML;
x = x.substr(0, x.search("<")).replace(/\s+/g, '-').toLowerCase();
x = onlyEngLetters(x);
searchButtons[i].setAttribute('id',x);
}
}
function onlyEngLetters(text) {
text=text.replace("ę","e");
text=text.replace("ó","o");
text=text.replace("ą","a");
text=text.replace("ś","s");
text=text.replace("ł","l");
text=text.replace("ż","z");
text=text.replace("ź","z");
text=text.replace("ć","c");
text=text.replace("ń","n");
return text;
}
</script>
Thank You for help!
Iterate the childnodes until you get to the first textNode that isn't empty to get the text you want. Note also thaat replace() only works on first instance found and you probably want to convery to lower case to match your replacements
addIDtoGI()
function addIDtoGI(){
document.querySelectorAll('.sf-label-radio').forEach(el=>{
let txtNode = el.childNodes[0];
while(!txtNode.textContent.trim()){
txtNode = txt.nextSibling
}
el.id = onlyEngLetters(txtNode.textContent);
console.log(el.id)
});
}
function onlyEngLetters(text) {
return text.toLowerCase()
.replaceAll("ę","e")
.replaceAll("ó","o")
.replaceAll("ą","a")
.replaceAll("ś","s")
.replaceAll("ł","l")
.replaceAll("ż","z")
.replaceAll("ź","z")
.replaceAll("ć","c")
.replaceAll("ń","n")
}
<label class="sf-label-radio">Name1<span>Some Other Text that I do not need</span><label>
<label class="sf-label-radio">Name2<span>Some Other Text that I do not need</span><label>
First, you define your function but you never call it.
In your script, add the "()" to "addIDToGI;": addIGToGI();
There's also a typo on searchButtons.lenght, it should be length.
It should resolve your errors.
EDIT: Also, as someone mentionned in the comments, <lable> should be <label>.
First you must call function with () and when using for loop must use variables=>
for(let i = 0; i < searchButtons.length; i++) . length is true not lenght. and of course
let x = searchButtons[i].innerHTML;
and ...
const addIdToClassByInnerHTML = cls => {
const elements = document.querySelectorAll('.' + cls);
elements.forEach(el=>{
el.setAttribute('id', el.innerHTML);
});
}
note that do not use this function if the element contains child.
if your element contains one or more child(ren), use this:
const addIdToClassByInnerHTML = cls => {
const elements = document.querySelectorAll('.' + cls);
elements.forEach(el=>{
let html = el.innerHTML;
el.querySelectorAll('*').forEach(sub=>{
html = html.replace(sub.outerHTML, '');
});
el.setAttribute('id', html);
});
}
codepen demo
snippets
const addIdToClassByInnerHTML = cls => {
const elements = document.querySelectorAll('.' + cls);
elements.forEach(el=>{
let html = el.innerHTML;
el.querySelectorAll('*').forEach(sub=>{
html = html.replace(sub.outerHTML, '');
});
el.setAttribute('id', html);
});
}
addIdToClassByInnerHTML('sf-label-radio');
console.log(document.querySelectorAll('.sf-label-radio')[0]);
label{
display: block;
}
<label class="sf-label-radio">Name1<span>Some Other Text that I do not need</span><label>
<label class="sf-label-radio">Name2<span>Some Other Text that I do not need</span><label>

Regular expression in javascript to get contents of <span> tags

I have a string with this form
<p>Central: <span class="fieldText">Central_Local</span>
<br>Area Resolutoria: <span class="fieldText">Area_Resolutoria</span>
<br>VPI: <span class="fieldText">VIP</span>
I'm trying to get the span elements, and find the values within
var message = currentMarker.get("mensaje");
var pat = new RegExp("^(.*?<span .*?>(.*?)</span>.*?)+$");
message.match(pat);
I need to get these values:
Central_Local
Area_Resolutoria
VIP
IP_ERX
How can this be done, or how can my regex be improved?
jQuery
var message = currentMarker.get("mensaje");
var contents = [];
$('<div>', {html: message }).find('span.fieldText').each(function(){
contents.push( $(this).text() );
});
demo at http://jsfiddle.net/DfDPR/2/
Pure javascript
var message = currentMarker.get("mensaje");
var contents = [];
var div = document.createElement('div');
div.innerHTML = message;
var spans = div.getElementsByTagName('span');
for (var span = 0; span < spans.length; span++)
{
contents.push(spans[span].innerHTML);
}
demo at http://jsfiddle.net/DfDPR/3/
As mentioned in the comments, regex is not a good candidate for parsing HTML...
Trivial task in jQuery:
var values = $('span.fieldText', message).map(function(){
return $(this).text();
}).get();
values will be an array with all the values you need. You can iterate over it or do anything you like.

How to get child element by ID in JavaScript?

I have following html:
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
How can I get textarea element? I can't use document.getElementById("textid") for it
I'm doing it like this now:
var note = document.getElementById("note");
var notetext = note.querySelector('#textid');
but it doesn't work in IE(8)
How else I can do it? jQuery is ok
Thanks
If jQuery is okay, you can use find(). It's basically equivalent to the way you are doing it right now.
$('#note').find('#textid');
You can also use jQuery selectors to basically achieve the same thing:
$('#note #textid');
Using these methods to get something that already has an ID is kind of strange, but I'm supplying these assuming it's not really how you plan on using it.
On a side note, you should know ID's should be unique in your webpage. If you plan on having multiple elements with the same "ID" consider using a specific class name.
Update 2020.03.10
It's a breeze to use native JS for this:
document.querySelector('#note #textid');
If you want to first find #note then #textid you have to check the first querySelector result. If it fails to match, chaining is no longer possible :(
var parent = document.querySelector('#note');
var child = parent ? parent.querySelector('#textid') : null;
Here is a pure JavaScript solution (without jQuery)
var _Utils = function ()
{
this.findChildById = function (element, childID, isSearchInnerDescendant) // isSearchInnerDescendant <= true for search in inner childern
{
var retElement = null;
var lstChildren = isSearchInnerDescendant ? Utils.getAllDescendant(element) : element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].id == childID)
{
retElement = lstChildren[i];
break;
}
}
return retElement;
}
this.getAllDescendant = function (element, lstChildrenNodes)
{
lstChildrenNodes = lstChildrenNodes ? lstChildrenNodes : [];
var lstChildren = element.childNodes;
for (var i = 0; i < lstChildren.length; i++)
{
if (lstChildren[i].nodeType == 1) // 1 is 'ELEMENT_NODE'
{
lstChildrenNodes.push(lstChildren[i]);
lstChildrenNodes = Utils.getAllDescendant(lstChildren[i], lstChildrenNodes);
}
}
return lstChildrenNodes;
}
}
var Utils = new _Utils;
Example of use:
var myDiv = document.createElement("div");
myDiv.innerHTML = "<table id='tableToolbar'>" +
"<tr>" +
"<td>" +
"<div id='divIdToSearch'>" +
"</div>" +
"</td>" +
"</tr>" +
"</table>";
var divToSearch = Utils.findChildById(myDiv, "divIdToSearch", true);
(Dwell in atom)
<div id="note">
<textarea id="textid" class="textclass">Text</textarea>
</div>
<script type="text/javascript">
var note = document.getElementById('textid').value;
alert(note);
</script>
Using jQuery
$('#note textarea');
or just
$('#textid');
$(selectedDOM).find();
function looking for all dom objects inside the selected DOM.
i.e.
<div id="mainDiv">
<p>Paragraph 1</p>
<p>Paragraph 2</p>
<div id="innerDiv">
link
<p>Paragraph 3</p>
</div>
</div>
here if you write;
$("#mainDiv").find("p");
you will get tree p elements together. On the other side,
$("#mainDiv").children("p");
Function searching in the just children DOMs of the selected DOM object. So, by this code you will get just paragraph 1 and paragraph 2. It is so beneficial to prevent browser doing unnecessary progress.

Categories

Resources