testing for element tag name - javascript

When a user enters a bookmark using form['f3'] (a url and a title) it is immediately entered in via the dom - visually the title and the favicon are seen by the user. Each bookmark is a link and and image under div Bb1c. The insert is done alphabetically. Basically, I need to insert the new image and link after the previous one.
The loop portion was created before I had added in favicons so it loops through all the child elements, but it only needs to loop through the tags. How do I check to make sure that it is an element of type a before doing a compare? My for loop needs an && added to it.
This is rough draft code so if there anything else - contstructive criticism
var a=document.getElementById('Bb1c'),
b=document.createElement('a'),
e=document.createElement('img');
c=document.forms['f3'].elements,
d=a.firstChild,
b.innerHTML=c[1].value;
b.href=c[2].value;
b.name="a1";
b.className="b";
e.src=b.hostname + '/favicon.ico';
e.onerror=function()
{
e.src = 'http://www.archemarks.com/favicon.ico';
}
while(d=d.nextSibling)
{
if(b.innerHTML<d.innerHTML)
{
break;
}
}
a.insertBefore(b,d);
return 1;
}

You want the tagName (or nodeName) property.:
if(ele.id === "foo" && ele.tagName.toLowerCase() === "span") {
// do something
}

Related

How to convert links to text using JQuery?

I try to think up function which can replace links to text. Image inside a tag should be moved to the wrapper, the original a should be removed.
JS:
var selectors = 'a.mark-video;a.sp5;a>img[alt!=""]'
selectors = selectors.split(";").join(", ");
$(selectors).each(function() {
var current = this;
if (this.nodeName == "IMG") {
current = this.parentNode;
if (current.nodeName != "A")
current = this.parentNode;
if (current.nodeName != "A")
return false;
current = $(current);
}
var wrapper = current.parent();
var new_context = $().append(current.html());
current.remove();
wrapper.append(new_context);
}
);
The problem is
1) that the image is not inserted into the wrapper
2) if it would be inserted it would not have correct position.
I am experimenting using webextensions API (Firefox addon) and I injected the code to site:
http://zpravy.idnes.cz/zahranicni.aspx
In the debugger you can see two wrappers with class="art ". I have removed the first link but image is not inserted. The second one has not been removed yet when debugger was paused after first iteraction.
I hope you can find out why the image is not appended and how to append it to the original position of the element a. I need to find out position of the element a first, and then to move the image into to correct position - that is before div.art-info.
Note: please do not change the selectors string. This is the users input from form field.
Edit:
Almost there:
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).html().replaceWith($(this)); // error: html() result does not have replaceWith...
}
Is this what you're looking for?
https://jsfiddle.net/4tmz92to/
var images = $('a > img');
$.each(images, function(key, image) {
$(this).parent().replaceWith(image);
});
First select all the images that you want to remove the link from, then loop through them and simply replace the parent() with the image.
I have finally solved the problem:
$(selectors).each(
function(){
if (this.parentNode.nodeName == "A")
$(this.parentNode).replaceWith($(this));
else
$(this).replaceWith(
$(this).html()
);
}
);
This works similar. Novocaine suggested not to use $(this).html() but this would skip some images so I prefer to use it.

Typewriter Script Stops Functioning after Run Once

I've been trying to get this typewriter function to run (please refer to JSFiddle below).
I set up an if-else statement so that when the user clicks on Biography the biography text is active and types itself out, and upon second click, the text becomes inactive and is erased. Ideally on a third click, the biography text will show up again, unfortunately this is when my code falls apart. It only runs once, and the text no longer shows up.
I tried console.logs and know that the DOM is registering when #bio has the class "active" attached to it, and when it does not, so I'm not sure why the typewriter script is not working the second time around.
var str = "<p>This is biography text.</p>",
i = 0,
isTag, text;
$('#biog').click(function () {
if ($("#bio").hasClass("active")) {
$("#bio").removeClass("active");
$("#bio").detach();
} else {
$("#bio").addClass("active");
(function type() {
text = str.slice(0, ++i);
if (text === str) return;
document.getElementById('bio').innerHTML = text;
var char = text.slice(-1);
if (char === '<') isTag = true;
if (char === '>') isTag = false;
if (isTag) return type();
setTimeout(type, 1);
}());
}
});
.active {
}
<div id="biog"><a>Biography</a>
</div>
<div id="bio"></div>
JSFiddle: http://jsfiddle.net/droogist/20L8088r/1/
There are two mistakes in you code.
You are detaching element after one use, because of that the second time you try accessing it, it is not there.
You are not resetting the variable i after one use.
So, use $("#bio").html(''); instead of $("#bio").detach();
And also, add i = 0; in else part of your code.
Here is the updated JSFiddle,
http://jsfiddle.net/20L8088r/2/

Getting Text out of HTML into Javascript as a Function with Input Changing IDs

I am trying to create an if/else statement that checks the text of a button that the user presses. If there is no text in that button, it continues the function, if there is pre-existing text then it gives an alert stating that there is already an entry there.
Essentially, the user clicks a button and the code checks to see if that button is empty or not. However, since the button's ID is constantly changing, I don't know how to tell the code to check the pressed button. I feel that using 'this' is part of the solution to this problem, but I am too new to JavaScript to use it correctly.
This is my entire JavaScript code, off it works fine except for the two lines that have comments in them. I am trying to make the variable "inSquare" to equal the text from the button that triggered the function. Then it goes on to check the text of the variable, but currently all it does is fail the if and head straight to the else.
var turnNumber = 9;
var whoseTurn;
var inSquare;
function currentTurn(id) {
inSquare = this.innerHTML; /*This Line*/
if (inSquare === "") { /*This Line*/
if (whoseTurn === 0) {
id.innerHTML = "X";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
} else {
id.innerHTML = "O";
turnNumber -= 1;
whoseTurn = turnNumber % 2;
}
} else {
window.alert("Something is already in that square!");
}
}
Also, here is an example of what the HTML buttons look like. (There are nine total, but they are all formatted the same).
<button id="topLeft" onclick="currentTurn(this)"></button>
<button id="topMid" onclick="currentTurn(this)"></button>
<button id="topRight" onclick="currentTurn(this)"></button>
inSquare = this.innerHTML; should be inSquare = id.innerHTML;
this in your function refers to the window object, but you want to refer to the element you passed, which you provided as the id argument of the function.

Convert URL in paragraphs to links using jQuery or Javascript

I am new to javascript but understand jQuery. I am trying to use this code to convert www. and http in p tags to working links.
Here is the code I am using, the problem is that I do not fully understand how the code works, could anybody please explain?
<script>
var re = /(http:\/\/[^ ]+)/g;
function createLinks(els) {
$(els).contents().each(function () {
if (this.nodeType === 1 && this.nodeName !== 'script') {
createLinks(this);
} else if (this.nodeType === 3 && this.data.match(re)) {
var markup = this.data.replace(re, '$1');
$(this).replaceWith(markup);
}
});
}
createLinks(document.body);
</script>
First, you set regular expression template for matching text which starts from "http://"
Second, you create recursive function which traverse whole html document.
nodeType == 1 means that current element is html tag (i.e. a, p, div etc)
nodeType == 2 means that element is Attribute
nodeType == 3 means that element is text node
So when you found html tag, you're searching inside it,
when you found text node, you are checking via regular expression, if this text starts from "http://", if so you change and replce this text to yourmatchedurl
in the end you call your function to start from body as a root
ok, here goes...
//create a regular expression to format the link
var re = /(http:\/\/[^ ]+)/g;
//this is the create links function which gets called below, "els" is the elements passed to the function (document.body)
function createLinks(els) {
//for each of the elements in the body
$(els).contents().each(function () {
//check if its an element type but not a script
if (this.nodeType === 1 && this.nodeName !== 'script') {
//call the create links function and send in this object
createLinks(this);
//if its not an element but is a text node and the format matches the regular expression
} else if (this.nodeType === 3 && this.data.match(re)) {
//create the markup
var markup = this.data.replace(re, '$1');
//finally, replace this link with the marked up link
$(this).replaceWith(markup);
}
});
}
//call the create links function
createLinks(document.body);
I hope the commented code helps you understand.

Check if contents of a DIV is only an Image

I have a div containing initially a loader image tag.
<img src="/images/indicator_big.gif" style="display:block;margin:auto">
I want to check if the DIV contains only the loader image then the function should trigger an Ajax Request.
If i do some thing like div.innerHTML I get it as a string.
What will be the best way to test if the innerHTML is only a loader image?
This method will do what you ask, although I'm not sure the general approach is the best to be honest.
function hasOnlyImg(div) {
if (div.children.length != 1)
return false;
return div.children[0].tagName == "IMG";
}
You can check how many elements are inside your element
var children = document.querySelector("#yourDiv > *");
if (children.length == 1 && children[0].tagName.toLowerCase() == "img") {
//you only have one child in here, and that's an image
}
This will be 1 if it only contains your initial image.
Be wary of the browser support, though: http://www.quirksmode.org/dom/w3c_core.html#t13
I'm assuming your 'style.display' of that loader image will change? You could just check for that?
function checkDiv(div,func) {
var thisDiv = div;
var imgLink = thisDiv.getElementsByTagName("img");
if (imgLink.length == 1 && imgLink[0].style.display !== "block") {
func();
}
}
checkDiv(document.getElementById("mydiv"),function() {
//call ajax code
});
Or if you still would like to check the number of HTML tags within your div, just do something like:
var allDivTags = mydiv.getElementsByTagName("*");
if (allDivTags.length == 1 && allDivTags.nodeName.toLowerCase() == "img") {
//only 1 html element exists in the div, and it's an image.
//run code
}
Hope this helps.

Categories

Resources