Extract innerHTML from a Javascript function - javascript

I apologise in advance if this has already been asked, but I couldn't find it. If it has, please direct me to the page and I won't bother you.
I've used a Javascript function to extract inner HTML. I'm able to console.log this, but I'd like to insert it in a new node/part of the HTML.
For example:
<h2>Example text id="article"</h2>
<p>'insert javascript text'</p>
<p>example</p>
<p>example</p>
<p>example id="pToExtract"</p> <--! this is the text i'd like to extract. I would like to feature it higher up in the html page, as well as here. -->
this is the function i've used to extract the text:
function printFirstLine(elem) {
let firstLine = document.getElementById(elem);
console.log(firstLine.innerHTML)
}
printFirstLine ("pToExtract")// this works. i can see the text in the console
the function i've used to place it where i'd like is:
let newText = '';
let menu = document.getElementById ('article');
let li = document.createElement('p');
li.textContent= newText;
menu.insertBefore(li, menu.firstElementChild.nextSibling);
this sort of works if i put text/a string on 'newText', and if I put the function name there it just returns the function, ie function () {} etc.
is there anyway to return the actual value/innerHTML of the function to say a new variable, so i can use it in the place of newtext or another way to accomplish this.
thank you

Not sure if I understand your question correctly but are you looking for this?
function printFirstLine(elem) {
const firstLine = document.getElementById(elem);
return firstLine.innerHTML; // here return the value
}
const newText = printFirstLine( 'pToExtract' );
Also I think you meant to write this:
<p id="pToExtract">example</p>
Instead of this:
<p>example id="pToExtract"</p>

Related

I am trying to trim the output of a jQuery function

I am modifying a third-party script so that I can style the output.
Here is a segment of the original code:
var tip_content = $('<div>').addClass('tip_content').load(url, function() {
Which produces this output:
<div class="tip_content">
I need to add another class to the output to style it differently on each page. Therefore, it seems like a good solution to add the current html page file name as a class.
But I have no experience with JS.
Here is what I've managed to mangle together:
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href')).load(url, function() {
Which produces this:
<div class="tip_content tickets.php?id=185">
This is almost exactly what I need. But I would be very grateful if someone could demonstrate how to trim the output to:
<div class="tip_content tickets">
You have to split the URL with . and takes the first-value from the splited array and add it to the div as second class.
Do it like below:-
var tip_content = $('<div>').addClass('tip_content '+elem.attr('href').split('.')[0]).load(url, function() {
A hard-coded example:-
var hrefs = "tickets.php?id=185";
$('div').addClass('tip_content '+hrefs.split('.')[0]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>Inspect and check my class</div>
try below code
s = elem.attr('href');
s = s.substring(0, s.indexOf('.'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {
I would like to add a modification to be safe. suppose your url is: tickets.sold.php and you want tickets.sold. In this case you should try this:
s = elem.attr('href');
s = s.substring(0, s.indexOf('.php'));
var tip_content = $('<div>').addClass('tip_content '+ s).load(url, function() {

Javascript that changes HTML code

Is it possible to make javascript to when you enter variables to add code to html..? I don't know English too good, so..I'm going to draw it!
Also, I don't want it to change everything, but I want it just to add that
info to the list..I have premade HTML page with linked CSS.
If you have any questions, please ask me, just help me.. :(
I know HTML and CSS, java..Not even a little bit.. :/
If you are here reading this, THANK YOU! <3
You have many options to add html to your page through JavaScript.
1) Simply create a div with an id
<div id="enterTextHere"></div>
2) Inside of your custom.js file or inside of <script></script>, you can use many different methods
Method 1 : Using innerHTML
var desiredElement = document.getElementById("enterTextHere");
desiredElement.innerHTML = "<p>I added text!</p>";
Method 2 : Using JQuery.append
$("#enterTextHere").append("I added text!");
I'm sure there are many more but without your specific code to reference this is the best I can do. Please use this link for your reference. It also has a lot of good information for the rest of your HTML journey. Enjoy! w3schools
Maybe something like this can help:
HTML:
<table class="table"><tr id="update-table"></tr></table>
<script>
(function(){
var updater = (function(){
function updater( options ){
this.table = options.table;
this.cells = this.table.querySelectorAll('.cell');
this.num_cells = this.cells ? this.cells.length : 0;
}
updater.prototype.update_element = function( index, value ){
this.cells[index].innerHTML = value;
};
updater.prototype.add_element = function(){
var td = document.createElement('td');
td.setAttribute('class','cell');
this.table.appendChild(td);
this.cells.push(td);
this.num_cells++;
};
return updater;
})();
window.updater = updater;
})();
var table, a, count = 0;
table = document.getElementById('update-table');
a = new updater({table:table});
for(var i = 0; i < 5; ++i){
a.add_element();
a.update_element(i,'info'+i);
}
</script>

Javascript: Return original innerHTML on mouseout

I am sorry for this very basic question. I am very new to javascript and learning it.
I am stuck with one easy problem-
This is what i am trying to do-
I have a header that has some innertext
<h1 id="bd" onmouseover="fun1()" onmouseout="fun2()"> sample</h1>
I am chaging innerHTML of this header on mouseover like this-
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
well on mouseout i do the same but for getting original innerHTML for this header tag.
function fun2()
{
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
}
But onmouseout function shows me changed innerHTML, that is a in this case.
How do i get original innerHTML sample again onmouseout?
I want this to be done in javascript.
I tried another way more
function fun1()
{
document.getElementById("bd").innerHTML="a";
}
function fun3()
{
var ds=document.getElementById("bd").innerHTML;
alert(ds);
}
function fun2()
{
document.getElementById("bd").innerHTML=fun3();
}
but it is not working also.
A very generic version would be the following:
First change your markup a bit:
<h1 id="bd" onmouseover="fun1(this)" onmouseout="fun2(this)"> sample</h1>
This way you don't need to look up your element again in your callback function. This works then for more than one element you mouse over. Then you go:
function fun1(elm) {
if (!fun1.cache) fun1.cache = {}; // extend your function with a cache
fun1.cache[elm.id] = elm.innerHTML; // write into cache -> fun1.cache.bd
elm.innerHTML = 'a';
}
function fun2(elm) {
if (fun1.cache && fun1.cache[elm.id]) { // see if cache exists and...
elm.innerHTML = fun1.cache[elm.id]; // read from it
}
}
This way you build a caching system that doesn't need an extra global variable but stays closer to your function.
The next step would be to use only one function and send the new value as a parameter. Create something like a toggle function:
<h1 id="bd" onmouseover="fun(this, 'a')" onmouseout="fun(this)"> sample</h1>
and then your function:
function fun(elm, newValue) {
if (!fun.cache) fun.cache = {};
var value = newValue || fun.cache[elm.id]; // no newValue means recover old value
fun.cache[elm.id] = elm.innerHTML; // alway save the old value
elm.innerHTML = value;
}
If you need more explanations about this and creating Objects just leave a comment to this answer and I'll come back with more details...
Good luck!!
Store the first innerHtml in a global variable ,and use this variable to backup the first innerHtml.
var oldInner = '';
function fun1()
{
oldInner = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=oldInner;
}
You'll need to store the original value somehow:
var originalInnerHTML = "";
function fun1()
{
originalInnerHTML = document.getElementById("bd").innerHTML;
document.getElementById("bd").innerHTML="a";
}
function fun2()
{
document.getElementById("bd").innerHTML=originalInnerHTML
}
Currently you just get the existing innerHTML and set it as the new innerHTML - it's always going to be the same. So this line never changes anything:
document.getElementById("bd").innerHTML=document.getElementById("bd").innerHTML;
once you have changed the innerhtml of an element, old data is gone
In order to get the old data you first need to have it store in some other place.
For ex : on mouseover you can first copy the original html to a hidden div, and upon mouseout you can again copy from the hidden div to the main div.
hope this helps.
A very easy implementation will be to have the two text you want to display in the div. so you have:
<h1 id="bd">
<span id='sample1'>sample1</span>
<span id='sample2' style='display: none'>a</span>
</h1>
var el = document.getElementById("bd");
el.onmouseover = function() {
document.getElementById("sample1").setAttribute("style", "display: none");
document.getElementById("sample2").setAttribute("style", "");
}
el.onmouseout = function() {
document.getElementById("sample2").setAttribute("style", "display: none");
document.getElementById("sample1").setAttribute("style", "");
}

move node from second to first

Just want a function that move second node to be a first node.But it not working, any suggestion?
var node = document.getElementById("ir");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.firstChild);
}
fullcode:
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,node.previousSibling);
}
http://jsfiddle.net/joeframbach/JSZPy/
The issue with the html in that fiddle is the spaces. childNodes[0] matches the first set of spaces, and childNodes[1] matches the first element. Perhaps this is your issue.
<div id="ir">
<p>First</p>
<p>Second</p>
</div>
var node = document.getElementById("ir");
var first = node.childNodes[1];
var second = node.childNodes[3];
node.insertBefore(second,first);
I'm a bit slow today, but I think your use of previousSibling is wrong. I think it should relate to the child node cx not the parent node .. so you should be using cx.previousSibling not node.previousSibling - I've edited mt previous example to remove my original dumb response ... try this ...
<div id="ir">
<p id="ie">test</p>
<img src="test.gif">
</div>
<script type="text/Javascript">
var node = document.getElementById("ir");
img.setAttribute("onclick","der()");
var cx = node.childNodes[1];
function der(){
node.insertBefore(cx,cx.previousSibling);
}
Two Days Later Edit !!! ....
Of course the example I gave above will not swap the P element and the image because the image's true previousSibling is a newline character between the /P tag closure and the image. More importantly from a coding perspective, it won't work because there isn't an object called 'img' defined anywhere ... so I offer this as a working alternative :
<script>
function swapDivs(obj) {
if(obj.previousSibling){ // if it's null, then it's already the first element //
obj.parentNode.insertBefore(obj, obj.previousSibling);
}
}
</script>
<div id="ir">
<p id="ie">test</p><img src="http://i2.ifrm.com/4639/142/emo/drool.gif" onclick="swapDivs(this);" />
</div>
It doesn't address the newline issue, I just reformatted the HTML.
However, it does resolve the img issue, and provides a generic way of adding the function to any clickable DOM object without having to customise the function.
I'll leave it to you to work out how to get over the problem with the newline/whitespace sibling, but it shouldn't be to difficult. Here's the fiddle to play with if you want to test your attempts ... http://jsfiddle.net/radiotrib/ps9XZ/
You've got an answer but i recommend doing something like:
var node = document.getElementById("ir");
var childs = node.getElementsByTagName("div");
var cx = childs[1];
function der()
{
node.removeChild(cx);
node.insertBefore(cx, childs[0]);
}
der();
I advise you not to put spaces or breaklines when working with childnodes, because they are considering like child of text type. I hope this code will help you:
Javascript code:
function change(){
var parent = document.getElementById("ir");
var img = parent.childNodes[1];
parent.removeChild(img);
parent.insertBefore(img, parent.firstChild);
}
HTML code:
<div id="ir"><p id="ie">test</p><img src="test.gif"></div>
<button onclick="change()">Change</button>

JavaScript/jQuery: hasDescendant / hasAncestor

Hilariously, I'm having incredible difficulty finding any half-good way to determine whether or not an HTML element is inside another one or not -- which seems like it should be a basic core feature of traversing and analyzing the HTML DOM. I was immensely surprised and disappointed that the "hasDescendant" (or likewise) method is missing.
I'm trying to do this:
var frog = $('#frog');
var walrus = $('#walrus');
if (frog.hasDescendant(walrus)) console.log("Frog is within walrus.");
else console.log("Frog is outside walrus.");
I've tried to reproduce what I'm looking for with many jQuery combinations.
walrus.is(frog.parents());
walrus.has(frog);
walrus.find(' *').has(frog);
frog.is(walrus.find(' *'));
I haven't found a working solution yet.
[edit]
Solution: walrus.has(frog)
Alternate: if (walrus.has(frog)) { doStuff(); }
Alternate: var booleanResult = walrus.has(frog).length>0;
//Chase.
jQuery has just the function for this: jQuery.contains: "Check to see if a DOM element is within another DOM element."
Demo (live copy):
HTML:
<p id="frog">Frog <span id="walrus">walrus</span></p>
JavaScript:
jQuery(function($) {
var frog = $("#frog"),
walrus = $("#walrus");
display("frog contains walrus? " + $.contains(frog[0], walrus[0]));
display("walrus contains frog? " + $.contains(walrus[0], frog[0]));
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
Use
if (walrus.has(frog).length) {
// frog is contained in walrus..
}
Demo at http://jsfiddle.net/gaby/pZfLm/
An alternative
if ( $('#frog').closest('#walrus').length ){
// frog is contained in walrus..
}
demo at http://jsfiddle.net/gaby/pZfLm/1/
If you wanted to write your own function you could do it without jQuery, perhaps something like this:
function isAncestor(ancestor, descendent) {
while ((descendent = descendent.parentNode) != null)
if (descendent == ancestor)
return true;
return false;
}

Categories

Resources