I have an orientational question that i'm not quite sure how to approach, so this is a request for advice.
For a project i'm working on i would like to assemble 'custom' variable names. For example, lets say i have this html page:
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Now i know i can get the id's in jQuery with $('div').attr('id'). This is where my problem comes in:
I would like to create something like this line:
var variable_name_custom = 'Hello world';
where the var-name is generated by getting the div id's. (string div 1 + string div 2 + string div 3).
If i were to put the 3 names together right now, i would get the string 'variable_name_custom', but it would be a string-value of a variable, rather than the name of one.
Is this possible?
I have no idea why you would want to do something like this but:
var varName = getName(); // will get you 'div1_div2_div3'.
window[varName] = 'Hello world';
alert(div1_div2_div3); // Hello World.
Now you can access the div1_div2_div3 global var you created.
Take a look at this Fiddle
Here you go: http://jsfiddle.net/lotusgodkk/wd99s/
window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')] = 'Sample';
console.log(window[$('div').attr('id')+'_'+$('span').attr('id')+'_'+$('p').attr('id')]);
<div id="variable"></div>
<span id="name"></span>
<p id="custom"></p>
I think your best bet is to change the var into a property of an object.
names = {};
names[id1+'_'+id2+'_'+id3] = 'Hello world';
Hi you can use map function of Jquery
HTML Code
<div id="content">
<div id="variable"></div>
<div id="name"></div>
<div id="custom"></div>
</div>
Javascript
$(document).ready(function () {
var varname = $("#content > div").map(function () {
return this.id || null;
}).get().join("_");
window[varname] = "Hello World";
console.log("varname = "+varname);
console.log("value = "+window[varname])
});
take a look at this fiddle
Hope this helps
Thanks,
Dhiraj
Related
Is this possible using JavaScript or JQuery, or anything else?
Say I have an HTML file like this
<div>
<p>Hello World</p>
</div>
And I want to turn "World" into a span element itself, like so (so that I can style just "World")
<div>
<p>Hello <span>World</span></p>
</div>
Since there are a lot of unknowns in your question, so I am assuming that you already know the string/word around which you want to add the html tag.
So keeping that in mind, following solution should work:
HTML:
<div>
<p id="my-text">Hello World, Again!</p>
</div>
JavaScript:
const stringToBeReplaced = "World"; // what you want to replace
const innerText = document.getElementById("my-text").innerText; //grab the text
const beginIndex = innerText.indexOf(stringToBeReplaced); // get text where string begins
// if string exists
if (beginIndex >= 0) {
const textWithTag =
"<span style='color: red'>" + stringToBeReplaced + "</span>";
const newString = innerText.replace(stringToBeReplaced, textWithTag);
// replace the text with new string
document.getElementById("my-text").innerHTML = newString;
}
Hope this is what you were asking and looking for.
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_replace3
str.replace solves the job. The comment of #Umer Hassan is correct.
This is my code:
var turn = 1;
var boardPiece;
var piece = [];
function init() {
boardPiece = document.getElementById("pages");
while (boardPiece.firstElementChild) {
if (typeof boardPiece.firstElementChild.id != 'undefined') {
piece.push(boardPiece.firstElementChild);
}
boardPiece.removeChild(boardPiece.firstElementChild);
}
document.getElementById("content").innerHTML = piece[0]; //My problem is here
}
init();
<div id="content">
</div>
<div id="pages">
<div id="page1" class="page">
...
</div>
<div id="page2" class="page">
...
</div>
</div>
The result is a text
[object HTMLDivElement]
not an element.
What's wrong with my .innerHTML? And what is typeof piece[0]? Is it text?
You need to replace your:
document.getElementById("content").innerHTML = piece[0];
with:
document.getElementById("content").innerHTML = piece[0].innerHTML;
What you are trying to do atm is to insert element (which is an object) as a plain text.
You need to use the .innerHTML along with your piece[0] variable like,
document.getElementById("content").innerHTML = piece[0].innerHTML;
Working Fiddle: https://jsfiddle.net/gs0yy50t/
Hope this helps!
The issue is that the type of piece[0] is not a string, but a HTML element. For that reason, in order to assign it to the content's innerHTML (which is a string), JavaScript is implicitly calling the piece[0].toString() method.
When calling the toString() method in HTML nodes (like most non-string objects in JavaScript), it returns a string representing the type of the object.
If you need to add the element piece[0] as child of content, then you should do:
document.getElementById("content").innerHTML = piece[0].outerHTML;
However, if what you need is to copy the content of one element into another, you should use the property innerHTML instead:
document.getElementById("content").innerHTML = piece[0].innerHTML;
Basically, both properties are strings with the HTML code of the element but outerHTML includes the element itself in the root.
I know scope in javascript in sometimes tough but this time I suspect the issue may be jQuery execution order. In the following code I try to define a simple HTML element (simulates a button) in javascript and pass different text to it when mounting it in HTML using jQuery:
var name;
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="content-item" id="things4">
<a href="aFabrica.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryfabrica"></div>
<script>
$(document).ready(function() {
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
<div class="content-item">
<a href="lojas.html">
<div class="itemHome">
<div class="bg" id="buttonsecondaryloja"></div>
<script>
$(document).ready(function() {
var name = "Loja";
$("#buttonsecondaryloja").after(buttonsecondary)
})
</script>
</div>
</a>
</div>
The problem is that I get the same text on both buttons: "Store" although in the first alert getting "Street" and in the second "Store"...
Does anyone know how to explain it?
The problem is that the buttonsecondary variable already contains the final HTML of the button because it's merely a concatenated string.
You need to generate the desired HTML each time:
function generateButton(name)
{
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Then:
var name = "A Fábrica";
$("#buttonsecondaryfabrica").after(generateButton(name));
And
var name = "Loja";
$("#buttonsecondaryloja").after(generateButton(name));
In your original code, you are creating a string with variables that are changed later on. When you change the variables, the string does not get updated because the variables are not bound. You need to create a new string if you want to pass in a new value for the name.
Change this:
var buttonsecondary = '<div class="buttonsecondary clicked"><p>'+name+'</p></div>';
To this:
function createSecondaryButton(name) {
return '<div class="buttonsecondary clicked"><p>' + name + '</p></div>';
}
Or, since you are using jQuery:
function createSecondaryButton(name) {
return $('<div>').addClass('buttonsecondary clicked')
.append($('<p>').text(name));
}
Then simply call the function:
$("#buttonsecondaryfabrica").after(createSecondaryButton('A Fábrica'));
$("#buttonsecondaryloja").after(createSecondaryButton('Loja'));
I have this simple string:
<div id="parent">
<div id="1" class="child">test</div>
</div>
How can I extract the id number (1) from this string?
With JQuery you can
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
var str = $('<div id="parent"><div id="1" class="child">test</div></div>');
console.log(str.find(':nth-child(1)').attr('id'));
</script>
Where nth-child is the target you want to get the id
var s = '<div id="parent"> <div id="1" class="child">test</div> </div>';
var d = new DOMParser().parseFromString( s, "text/xml" );
var id = d.firstChild.childNodes[1].attributes['id'];
console.log( id );
var htmlString = '<div id="parent"><div id="1" class="child">test</div></div>';
var number = /id="(\d)"/.exec(htmlString)[1];
console.log(number); //outputs the number
You would have to do a match on the string object that the HTML is stored in. so, if the string is called htmlString, then you would do something akin to
var id = htmlString.match(/id=\"([0-9]+)\"/)
That SHOULD net you the result, but if you deal with any data that is more complex than the example you've been given, you would need a different regex.
<script>
let num = document.getElementById('1')
let ans = parseInt(num.id)
</script>
Although I am unsure as to what you are trying to accomplish, one way of getting of doing this is s to gather all like tagnames ("div" in this case) into an array and select the array index you desire (1 in this case) then reference the id - as follows:
var list=document.getElementsByTagName("div")
alert(list[1].id);
Am now facing an other challenge. Some parts of my html code has the following lines:
<div class="action-body flooded"><p>(In <span class="error">[82681]</span>) refs AGLBD-16096<br/></div>
I have to get the number with-in the [] and then replace it with a hyperlink. I have tried using document.getElementsByClassName('error') but its not working. how can I make it work? and i would also need to iterate in a loop to replace all such numbers if there are more than one in []. e.g: [123] [234] [345]...
This is all what I have written till now with pimvdb's help:
<script type="text/javascript">
var bodyText = document.getElementById('body').innerHTML;
var pattern = /\[.*?\]/g;
var replaceText = "Pradeep";
document.getElementById('body').innerHTML = bodyText.replace(pattern, replaceText);
</script>
This JSFiddle does what you need: http://jsfiddle.net/TNyms/
When you replace getElementById('body') with document.body, the code works for me.
var body = document.body;
var link = "Pradeep";
body.innerHTML = body.innerHTML.replace(/\[.*?\]/g, link);
That replaces all IDs in this with links:
<div class="action-body flooded">
<p>(In
<span class="error">[82681]</span>) refs
AGLBD-16096
<br/>
</div>
<div>[123][abcd]</div>
<div>[456]</div>
<div>[789]</div>
Outputs:
(In Pradeep) refs AGLBD-16096
PradeepPradeep
Pradeep
Pradeep
Try it with this fiddle.
Your question appears to be related to what is asked in the below link. You may refer this
Replace number in a string using regex or something else