InnerHTML + find() not working - javascript

I've been searching and trying different codes, but I don't came up to a solution.
This script i'm trying to create do this:
When the user clicks inside a div with class="Box". The program will save in a variable the content of the Box.
var boxContent = $(this).parents('.Box')[0].innerHTML;
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
<div class="Box">
<div class="URL_ID">
<span>http://test.com</span>
<span id="ID">3232434</span>
</div>
<div class="info">
</div>
<div class="secondLink">
</div>
</div>
Now what i'd like to take is the div to process later and do an append in a table. So i tried to use find(), but doesn't work...
var url = boxContent.find('.BoxSongUrl');
What can i do??
Thanks in advance.

Your statement:
So, the value of the variable boxContent now (acording to my html output will be) returns the hole div that the user clicked:
Is not true. innerHTML returns a string of the markup html inside the element. To use the Jquery's .find() method, you have to actually select the Jquery object:
var url = $(this).parents('.Box').find('.BoxSongUrl');

You can use clone to retain a copy of the first '.Box' element at the time the query is run.
var boxContent = $(this).parents('.Box').first().clone();
Then, you can use the find method on boxContent
var url = boxContent.find('.BoxSongUrl');
EDIT:
If you would rather not clone the whole jQuery object you would save the html and re-parse it before calling find.
var boxContent = $(this).parents('.Box').first().html();
Then, re-parse the HTML into a jQuery object:
var url = $(boxContent).find('.BoxSongUrl');

Related

How to get whole element, innerHTML gets only inner part?

I have a function that gets the product and the id of this product, I need to put the entire HTML into local storage, I try it like this, but the innerHTML gets only the inner part, please tell me how to fix it?
function storagePlusQuantity(product, productId) {
const storageId = 'product' + productId;
localStorage.removeItem(storageId);
localStorage.setItem(storageId, product);
console.log(product)
}
The photo shows an example of the product of which I receive a functionenter image description here
If you have code like this:
<div id="outer-div">
~~something~~
</div>
getting the innerHTML of the div will only get the ~~something~~ part.
What you want to do is just get the div with outerHTML.
See codepen example: See Codepen Here
innerHTML returns the HTML code or text inside the selected element and outerHTML returns the elements whole code.
Let's see by examples
innerHTML Example
<div id="container">Whoa!</div>
<script>
var x = document.getElementById('container').innerHTML;
console.log(x);
</script>
Output (In the console)
Whoa!
In the above code you can see JavaScript returns the code inside the selected element
outerHTML Example
<div id="container">Whoa!</div>
<script>
var x = document.getElementById('container').outerHTML;
console.log(x);
</script>
Output (In the console)
<div id="container">Whoa!</div>
As you can see outerHTML returns all the elements code including tag, attributes and also the inner code
This Is The Difference Between InnerHTML and outerHTML.
Although outerHTML is rarely seen

How to assign HTML text to a JavaScript variable?

Is it possible to assign HTML text within an element to a JavaScript variable? After much Googling, I note that you can assign HTML elements to a variable, but I want the actual text itself.
Details about my goal:
I am currently working on a CRUD application, and with the click of a delete button, a modal will display and ask the user for confirmation before deleting the record. Once the button has been clicked, I want to retrieve HTML text within a specific element used for AJAX call data. However, what I have tried so far is not being logged to the console; even when I change the global variable to var deleteLocationID = "test"; I doubt the modal displaying will affect the click function?
The code:
var deleteLocationID;
$("#deleteLocationBtn").click(function () {
deleteLocationID = $(document).find(".locationID").val();
console.log(deleteLocationID);
});
What I have tried so far:
Changing "deleteLocationID = $(document).find(".locationID").val();" to the following variations:
deleteLocationID = $(document).find(".locationID").html();
deleteLocationID = $(".locationID").val() / deleteLocationID = $(".locationID").html();
deleteLocationID = document.getElementsByClassName("locationID").value;
Any help would be much appreciated.
Use the text() method from JQuery, with this you can get the text inside of your element.
Use this way, it may help you:
deleteLocationID = $(document).find(".locationID").text()
Here is example of getting text from class element:
$('.locationID').text()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<div class="locationID">45</div>
It depends on the type of element you are trying to find your value.
for input types you can find the value by .val() in jQuery like:
$(document).find(".locationID").val();
you can grab innerHTML of the element by .html() in jQuery like:
$(".locationID").html();
but if you want to grab innerText of an element you can use .text() in jQuery like:
$(".locationID").text();

Creating dynamic divs

Trying to make a dynamic div but i don't know how. Wrote a solidity smart contract that accepts an array of struct. In the smart contract i can use a get function to display the data inside. Data in the array is treated like a history, it consists of amount (making a crowdfund site), date, currency used, etc. Since the get function in the smart contract can only extract one part of the array, i thought of putting the get function into the while loop and extract the whole history array..
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
I'm trying to dynamically create another div with the same amount of < a > in the div. If i had 10 sets of data to display in that div, i wish to create only 10 sets of that div. Can createElement() be used to do that? Couldn't find any solution that works. Totally have no idea on how to create it. Can someone please help.
Would it be rational to extract the data from the array using a while loop and putting it in a div to display or would it use too much gas for this to work?
I don't get why would you want to do this, but you can do like this:
$('#set a').each(function(){
$('#set').after( "<div></div>");
});
It selects all of the <a>...</a> inside the <div id="set">...</div> element, and for each one of those inserts a <div></div> element. It inserts the element right next to #set but you can change that to any other element you could select.
I'm supplying jQuery code since you tagged the question as jQuery.
Hope it helps,
You can get the number of anchor tags by using this function getElementsByTagName('a').length from the hosting div. Then use that number to create new divs. This solution is done using vanilla JS.
function createDynamicDivs(){
var newDiv = document.createElement("div");
var noOfAnchors = document.getElementById('set').getElementsByTagName('a').length;
for(var i=0;i<noOfAnchors;i++){
var newContent = document.createElement("a");
newContent.textContent= "Test ";
newDiv.appendChild(newContent);
}
document.getElementById('new').appendChild(newDiv);
}
<div id=set>
<a>value1</a>
<a>value2</a>
</div>
<div id="new"></div>
<button onclick="createDynamicDivs()">Generate</button>

change name of DIV width JavaScript

I am using following code:
...
<div id="divcontainer1">
...
<div id="divcontainer2">
...
</div>
</div>
...
Now, I want change "divcontainer2" at a later point of time in the Div "divcontainer3".
What is the right way to check is exist divcontainer2 and when true,
change in divcontainer2 width javascript ?
Thank you,
Hardy
It is probably not nest practice but you can do this by changing the .outterHTML of the element. You would likely want to improve on this but here is a quick example. The last line checks if div 2 exists.
var div2 = document.getElementById("div2");
var html = div2.outerHTML;
var idx = html.indexOf(">");
var newtag = html.substring(0, idx).replace("div2", "div3");
div2.outerHTML = newtag + html.substring(idx, html.length - 1);
var contents = document.getElementById("div3").innerHTML;
alert(document.getElementById("div2") != undefined);
All you do is
get the element .outterHTML
get the substring representing the tag.
Replace the text that defines it
Set the .outterHTML tag to our new string
Now you have a newly named div that keeps all of its attributes, position in the parent and content.
The alert line is how you check for the existence of an object.
I don't believe that there is a "proper" way to do this, however I would store the contents of divcontainer2 in a variable, and then do something like this
var containerOfDivContainer2 = document.getElementById("containerofdiv2");
containerOfDivContaier2.innerHTML = "<div id='divcontainer3'>"/* insert div contents */+"</div>";
Of course, this requires you to put divcontainer2 in a div called containerofdiv2 but it works.
If using jQuery, this will do it:
$('#divcontainer2').attr('id','divcontainer3');
But you shouldn't be changing IDs. Use classes instead and then use the jQuery's toggleClass() function, like:
<div id="divcontainer1">
...
<div id="divcontainer2" class="style1">
...
</div>
$('#divcontainer2').toggleClass("style1 style2");

jQuery "add" Only Evaluated When "appendTo" Called

this has been driving me crazy since yesterday afternoon. I am trying to concatenate two bodies of selected HTML using jQuery's "add" method. I am obviously missing something fundamental. Here's some sample code that illustrated the problem:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<p id="para1">This is a test.</p>
<p id="para2">This is also a test.</p>
<script>
var para1 = $("#para1").clone();
var para2 = $("#para2").clone();
var para3 = para1.add(para2);
alert("Joined para: " + para3.html());
para3.appendTo('body');
</script>
</body>
</html>
I need to do some more manipulation to "para3" before the append, but the alert above displays only the contents of "para1." However, the "appendTo appends the correct, "added" content of para1 and para2 (which subsequently appears on the page).
Any ideas what's going on here?
As per the $.add,
Create a new jQuery object with elements added to the set of matched elements.
Thus, after the add, $para3 represents a jQuery result set of two elements ~> [$para1, $para2]. Then, per $.html,
Get the HTML contents of the first element in the set of matched elements or set the HTML contents of every matched element.
So the HTML content of the first item in the jQuery result ($para1) is returned and subsequent elements (including $para2) are ignored. This behavior is consistent across jQuery "value reading" functions.
Reading $.appendTo will explain how it works differently from $.html.
A simple map and array-concat can be used to get the HTML of "all items in the result set":
$.map($para3, function (e) { return $(e).html() }).join("")
Array.prototype.map.call($para3, function (e) { return $(e).html() }).join("")
Or in this case, just:
$para1.html() + $para2.html()
Another approach would be to get the inner HTML of a parent Element, after the children have been added.

Categories

Resources