manipulating tag using java script - javascript

I am fairy new in learning JavaScript , I am practising to manipulate a tag,
here is my code
I know that I am making a silly mistake here but I am not sure which part has went wrong ?
could any one please give me some hint ?
<html lang='en'>
<head>
<meta charset="UTF-8" />
<title>
HTML Hyperlinks
</title>
</head>
<body>
<h1>
HTML Hyperlinks
</h1>
<p>
Here is a link to <a name = "hyper" href="http://yahoo.com/">page</a>.
The text around the link is not part of the link.
</p>
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
</body>
</html>

getElementsByTagName says elements. Plural.
It returns a NodeList, which is like an Array, not a single Element.
You need to loop over its return value (e.g. with for) or access it by index ([0])

You are requesting a collection of a tags, but then treating them like a single entity.
<script>
var element = document.getElementsByTagName("a");
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
try this
<script>
var element = document.getElementsByTagName("a")[0];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
</script>
or
<script>
var elements = document.getElementsByTagName("a");
for(var i = 0; i < elements.length; i++)
{
var element = elemenets[i];
var attribute = element.getAttribute("href");
element.setAttribute("href","Http://google.com");
element.setAttribute("target","_blank");
}
</script>

Change this line
var attribute = element.getAttribute("href");
to this
var attribute = element[0].getAttribute("href");

Related

How to reduce javascript code that use JQuery and .each()

I have tried to reduce following code
var wgDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.each
(function(nIndex)
{
var sWidgetName = $(this).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
});
to this code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.children(":first-child");
var sWidgetName = jqDialog.attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
but this doesn't work !
The sWidgetName variable is always undefined in last code.
What is my mistake ?
With help of comments, I have found a solution.
I must use get(0) to obtain first element in list returner by JQuery().
And I must use $(jqDialog) instead of jqDialog to get 'data-widgetvar' attribute.
Here is my new code
var jqDialog
= jQuery(".ui-dialog.ui-overlay-visible",window.parent.document)
.get(0);
var sWidgetName = $(jqDialog).attr('data-widgetvar');
var wgDialog = window.parent.PF(sWidgetName);
Assuming you want to access an element with attribute data-widgetvar nested in an element having css classes ui-dialog and ui-overlay-visible you could do the following with plain javascript:
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
querySelector allows a CSS like selector combining class together with attribute selector.
Update:
Here is a working example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Test</title>
<script type="text/javascript">
function main() {
var myElement = document.querySelector('.ui-dialog.ui-overlay-visible [data-widgetvar]');
console.log("Attribute value", myElement.getAttribute('data-widgetvar'));
}
document.addEventListener("DOMContentLoaded", main);
</script>
</head>
<body>
<div class="ui-dialog ui-overlay-visible">
<div>some element</div>
<div data-widgetvar="someValue">some text content</div>
</div>
</body>
</html>

How to display string length in javascript

I am new to javascript, and today i was trying my first example as shown below in the code section. I am using an editor called "Free Javascript Editor".
when I run the code, the browser starts and the text between the tags is displayed but the length of the string is never shown.
am I using it wrong?? please let me know how to do it correctly
lib
compile 'io.reactivex.rxjava2:rxjava:2.0.1'
compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
code:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = new string ("MyString");
str.length;
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Use Onload event and put it inside js function.
<body onload="myFunction()">
<script>
function myFunction() {
var str = ("MyString");
var n = str.length;
document.getElementById("printlength").innerHTML = n;
}
</script>
<h2>My First JavaScript</h2>
<p id="printlength"></p>
</body>
Use document.createElement
var str = "MyString";
var p = document.createElement("p");
p.textContent = str.length;
document.body.appendChild(p);
Scripts are not rendered by the browser, only executed. You can, however, do something like this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<h2>My First JavaScript</h2>
<p id="theLength"></p>
<script>
// No need to invoke the string constructor here.
var str = 'MyString';
// Find our placeholder element and set the textContent property.
document.getElementById('theLength').textContent = str.length;
</script>
</body>
</html>
It's good practice to put your script tags at the end of the body element - that way all of the HTML should render before the scripts are executed.
You should assign the length of your string to a variable. Then, you can show it.
<span id="stringLength"></span>
<script>
var str = "MyString";
var length = str.length;
document.getElementById('stringLength').textContent = 'Length: ' + length; // Show length in page
console.log('Length: ' + length); // Show length in console
alert('Length: ' + length); // Show length as alert
</script>
It must be String, not string. Code below works.
var str = new String ("MyString");
str.length;
Changed your code to this:
<html>
<head>
<title>Title of the home pahe</title>
</head>
<body>
<script>
var str = "MyString";
console.log(str.length);
</script>
<h2>My First JavaScript</h2>
</body>
</html>
Then you must look in the developer console for the output, here is how:
Google Chrome
FireFox
Safari

Javascript reusing forms

I want to get the names of the n (say n==5) children of a given person, by using the same form each time.
I can't seem to be able to produce javascript code that will accomplish this simple task.
for (var i = 0; i<5; i++){
<form id="child_form">
Child name:
<input type="text" id="child_name" name="child_nm" size="40">
<br>
<input type="button" value="Submit" onclick="myFunction()">
</form>
}
<script language="javascript">
<script>
function myFunction() {
add_child_to_array();
}
var array_of_children = [];
function add_child_to_array(){
var input_string = document.getElementById("child_name").value;
alert(input_string);
array_of_inputs.push(input_string);
}
</script>
But clearly one can't do that.
I've tried taking the data out of the form and then resetting the form. It turns out you can do either but not both.
I haven't found a website that deals with this problem.
Help would be greatly appreciated.
You have multiple options to accomplish this task. I would prefer to use the HTML5 template element functionality.
You could alternatively create and append the DOM Elements by yourself.
This is certainly a bit of a mess. Assuming I understand correctly, you need to create the form in javascript, so it can be dynamically added as many times as you want. I have written a generalised way of doing this. You may want to change / simplify it. I have made sure all elements are dynamic so that can be accessed properly. Also, I have used JQuery which I highly suggest.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script type="text/javascript">
$(function(){
var allForms = document.getElementById("all-forms");
for(var i = 0;i<5;i++){
form = document.createElement("div");
form.id = "form-" + i.toString();
if(i!=0){
form.style.display = "none";
}
input = document.createElement("input");
input.id = "child_name"+i;
input.placeholder = "input"+i;
submit = document.createElement("button");
submit.innerHTML = "go"+i;
submit.id = "submit-"+i;
submit.className = "buttons";
form.appendChild(input);
form.appendChild(submit);
allForms.appendChild(form);
}
$(".buttons").click(function(){
var id = $(this).attr("id").substring(7);
$("#form-"+id).hide();
var nextID = (parseInt(id)+1).toString();
$("#form-"+nextID).show();
});
});
</script>
</head>
<body>
<div id = "all-forms"></div>
</body>
</html>

Can you use a variable in a url path?

My app has html pages with content in different languages. Id like to use a variable (that is set when selecting a language) in a url like this:
<a href="/language/*variable*/product.html">
edit: I got marked down so to add more info lets says I set this when the page loads
var language = english;
There will be links in the app to change that to other languages ;-)
Let your tag look like this
<a id="link" href="#">Click Me!</a>
Let your variable be called prod.
Add these lines to your javascript wherever you want to update the url.
var hyperl = document.getElementById("link");
hyperl.href = "/language/" + prod + "/product.html";
EDIT:
Use this HTML
<a id="link" href="/language/LANG/product.html">Click Me!</a>
Use this javascript (or similar) to make all links point to the same language (variable name prod):
var links = document.getElementsByTagName("a");
for (i=0; i<links.length; i++) {
var hyperl = links[i];
hyperl.href.replace(LANG, prod);
}
You can use jQuery to dynamically generate the URL.
var string = '/language/'+variable+'product.html';
$(a#language).attr('href', string);
You can use a Javascript function to dynamically replace all href attributes of any <a> tags on the page like so:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Example</title>
<script>
"use strict";
function setLanguage(lang) {
var elements = document.getElementsByTagName('a')
for (var e = 0; e < elements.length; ++e)
{ elements[e].href = elements[e].href.replace(/\?hl=[A-za-z]*/, "?hl=" + lang); }
}
</script>
</head>
<body>
<h1>Search with Google</h1>
<ol>
<li>Search for <b>Python</b></li>
<li>Search for <b>Ruby</b></li>
<li>Search for <b>Javascript</b></li>
</ol>
<br>
<small>
Language:
en
de
</small>
</body>
</html>
In the example above, the ?hl=xxx part of the url is replaced via a regex whenever one of the en or de buttons is pressed.

stuck with javascript-html output

I am kind of stuck in weird problem. i cant find the problem with the following code
<html>
<head>
<script type="text/javascript">
// Import GET Vars
document.$_GET = [];
var urlHalves = String(document.location).split('?');
if(urlHalves[1]){
var urlVars = urlHalves[1].split('&');
for(var i=0; i<=(urlVars.length); i++){
if(urlVars[i]){
var urlVarPair = urlVars[i].split('=');
document.$_GET[urlVarPair[0]] = urlVarPair[1];
}
}
}
var tag_tag=document.$_GET['tags'];
alert(tag_tag);
document.getElementById("resultElem4").innerHTML=tag_tag;
</script>
</head>
<body>
<p id='resultElem4'></p>
</body>
</html>
its showing the string in alert but not in html when i call it like result.php?tags=cat
Put your script tag at the bottom (right before the closing body tag). The issue is that the element resultElem4 hasn't loaded when you try to reference it using getElementById.
You just move the < script > to the end of the body.
<body><p></p><script>....</script></body>

Categories