i tried to append all my CSS code into my javaScript and then load it trough js file,i do this,where is the problem?here is the first lines of my js file:
var innerstyle = '#container{width:800px;background:silver;margin:20px auto;padding:10px;color:gray;border-radius:5px}input{padding:3px}input[name="jsvar"]{width:250px;font-family:courier}#display{border:2px gray solid;border-radius:5px;color:white;margin:10px 0}#display #dtitle{background:gray;border-radius:2px 0;padding:10px 5px}#display #dmsg{min-height:20px}#clear{float:right;cursor:pointer;text-decoration:none;color:white;background:red;padding:2px 10px;border-radius:5px}#clear:hover{background:gold}.rtitle{padding:8px;background:pink;text-align:center}.rtitle input{border:1px solid red;float:right}.rtext{max-height:200px;overflow:auto;margin-bottom:5px}.rtext td{min-width:100px}.secfilter{margin-left:5px}';
var styletag = document.createElement('style');
var inst = document.createTextNode(innerstyle);
styletag.appendChild(inst);
var headref = document.getElementsByName('head');
headref.appendChild(styletag);
and here is the chrome console message:
Uncaught TypeError: undefined is not a function
Line 6;
var innerstyle = '#container{width:800px;background:silver;margin:20px auto;padding:10px;color:gray;border-radius:5px}input{padding:3px}input[name="jsvar"]{width:250px;font-family:courier}#display{border:2px gray solid;border-radius:5px;color:white;margin:10px 0}#display #dtitle{background:gray;border-radius:2px 0;padding:10px 5px}#display #dmsg{min-height:20px}#clear{float:right;cursor:pointer;text-decoration:none;color:white;background:red;padding:2px 10px;border-radius:5px}#clear:hover{background:gold}.rtitle{padding:8px;background:pink;text-align:center}.rtitle input{border:1px solid red;float:right}.rtext{max-height:200px;overflow:auto;margin-bottom:5px}.rtext td{min-width:100px}.secfilter{margin-left:5px}';
var styletag = document.createElement('style');
var inst = document.createTextNode(innerstyle);
styletag.appendChild(inst);
//var headref = document.getElementsByName('head'); // Wrong!
var headref = document.getElementsByTagName('head')[0];
headref.appendChild(styletag);
HTML DOM getElementsByName
returns a collection of all elements in the document with the specified name (the value of the name attribute)
("name" attribute deprecated in HTML5 and replaced by "id" attribute for many elements. You should use getElementById thanks #t.niese)
like
<input name="somename" />
document.getElementsByName("somename");
instead you could use the ID of the tag like
<input name="somename" id="theId" />
and query the element with:
document.getElementById('theId')
getElementById returns the element that has the ID attribute with the specified value
HTML DOM getElementsByTagName(tag) find all elements with the tag name "tag" and return an array, if you find by the tag name 'head' the first position in the array, would be the head element.
This function document.getElementsByName('head'); returns array. Try maybe something like this
document.getElementsByName('head')[0]
Its would give you first finded element with name head
Related
I want to extract all the HTML tags like from this <body id = "myid"> .... </body> i just want to extract <body id ="myid"> similarly i want to extract all the HTML tags with attributes and using javascript.
I've tried using regex to make an array of all the tags inclosed between '< & >'
<script>
$(document).ready(function(){
// Get value on button click and show alert
$("#btn_parse").click(function(){
var str = $("#data").val();
var arr = str.split(/[<>]/);
$('#result').text(arr);
});
});
</script>
but it's creating an array arr containing empty and garbage also it's removing angular brackets '<>'
which I don't want.
SO in nutshell I want a script that takes
str ='mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...';
and produces an array like:
arr = ["<htmltag id='myid' class='myclass'>","</htmltag>",...];
Here is one dirty way. Add it to the dom so it can be accessed via normal DOM functions, then remove the text, and split the tags and push to an array.
str ="mystring ... <htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag> ...";
div = document.createElement("div");
div.innerHTML = str;
document.body.appendChild(div);
tags = div.querySelectorAll("*");
stripped = [];
tags.forEach(function(tag){
tag.innerHTML = "";
_tag = tag.outerHTML.replace("></",">~</");
stripped.push(_tag.split("~"));
});
console.log(stripped);
document.body.removeChild(div);
Assuming you can also get the input from a "live" page then the following should do what you want:
[...document.querySelectorAll("*")]
.map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
The above will combine the beginning and end tags into one string like
<div class="js-ac-results overflow-y-auto hmx3 d-none"></div>
And here is the same code applied on an arbitrary string:
var mystring="<div class='all'><htmltag id='myid' class='myclass'>i_don't_want_anythin_from_here</htmltag><p>another paragraph</p></div>";
const div=document.createElement("div");
div.innerHTML=mystring;
let res=[...div.querySelectorAll("*")].map(el=>el.outerHTML.match(/[^>]+>/)[0]+"</"+el.tagName.toLowerCase()+">")
console.log(res)
I have created a script that creates an inner element in a HTML div element.
It works fine, but I think the way I did it using a string is not the most suitable in JavaScript.
HTML
<body>
<div class="chart-container">
<div class="chartlyrics">...</div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
Where the "..." are is where I created the element.
Javascript
document.getElementsByClassName('chartlyrics')[0].innerHTML = '<img src="img/103-logo.jpg" class="" /><br />Powered by '
HTML Result:
<body>
<div class="chart-container">
<div class="chartlyrics"><img src="img/103-logo.jpg" class="" /><br />Powered by </div><div class="chartlyrics box" id="powered_by"></div>
</div>
</body>
How can I do this but without using a string when creating the element in JavaScript?
I tried this but it gives me a syntax error:
document.getElementsByClassName('chartlyrics')[0].innerHTML = ''
var img = document.getElementsByClassName('chartlyrics')
.appendChild(document.createElement("img"));
img.src = "img/103-logo.jpg"
img.class = ""
img.textContent = 'Powered by '
console.log(document.getElementsByClassName('chartlyrics')[0].innerHTML);
Result:
document.getElementsByClassName (...). appendChild is not a function
You need to access the first element of the HTMLCollection and append the <img> element to that. Furthermore, store the newly created element in a variable first so you can set properties before appending. To add a line break and text after the image, you can append a newly created <br> element and use .append to add text.
const parent = document.getElementsByClassName('chartlyrics')[0];
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-logo.jpg"
img.setAttribute('class', "")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');
However, finding every single element with a specificied class to obtain only one element is extremely wasteful. You should use document.querySelector to obtain the first element matching a selector.
const parent = document.querySelector('.chartlyrics');
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-logo.jpg"
img.setAttribute('class', "")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');
I have a string with some variable html saved inside, among which a div with static id="time",
example:
myString = "<div class="class">blahblah</div><div id="time">1:44</div>"
How can I create a new identical string cutting off only the time? (1:44 in this case).
I can't look for numbers or the ":" because is not safe in my situation.
What i've tried without success is this:
var content = divContainer.innerHTML;
var jHtmlObject = jQuery(content);
var editor = jQuery("<p>").append(jHtmlObject);
var myDiv = editor.find("#time");
myDiv.html() = '';
content = editor.html();
console.log('content -> '+content);
var myString = '<div class="class">blahblah</div><div id="time">1:44</div>';
//create a dummy span
//put the html in it
//find the time
//remove it's inner html
//execute end() so the jQuery object selected returns to the span
//console log the innerHTML of the span
console.log($('<span>').html(myString).find('#time').html('').end().html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can achieve this using a regular expression in plain javascript like so:
myString.replace(/(<div id="time">).*(<\/div>)/, '$1$2')
If you want to extract only the 1:44 portion you can use the following:
myString.match(/(<div id="time">)(.*)(<\/div>)/)[2]
I was searching javascript code to get the content of HTML tag having attribute name ng-if="desc.description" using javascript querySelectors.
<li ng-bind-html="esc.description" ng-if="desc.description">Hello world.</li>
Use an attribute selector.
var contents = document.querySelector("[ng-if='desc.description']").innerHTML
Use getAttribute() method
Your Element
<script>
var a = document.getElementById('hey')
var x = a.getAttribute('ng-if') // "/"
alert(x);
</script>
Define Id value.
HTML:
<li id="id-ex" ng-bind-html="esc.description" ng-if="desc.description">Hello world.</li>
JS:
var myInnerHtml = document.getElementById("id-ex").innerHTML;
I need to write some html with placeholder used for javascript.
ex:
<span><placeholder data-id="42" data-value="abc"/><span>
Later on, a script will access those placeholders and put content in (next to?) them.
<span><placeholder data-id="42" data-value="abc"><div class="Google"><input type="text" value="abc"/></div><span>
But the placeholder tag doesn't exist. What tag can be used? Using < input type="hidden" .../> all over feels wrong.
Creating Custom tag
var xFoo = document.createElement('placeholder');
xFoo.innerHTML = "TEST";
document.body.appendChild(xFoo);
Output:
<placeholder>TEST</placeholder>
DEMO
Note: However creating hidden input fields with unique ID is good practice.
give your span element an id like,
<span id="placeToAddItem"><span>
and then in jQuery,
$('#placeToAddItem').html('<div class="Google"><input type="text" value="abc"/></div>');
or else
var cloneDiv = $('.Google');
$('#placeToAddItem').html(cloneDiv);
Example
The best way to do this, is using <input type='hidden' id="someId" value=""> tags.
Then you can easily access them by using jQuery, and recall the variable or change it.
var value = $("#someId").val(); to get variable or $("#someId").val(value) to change it.
This complete, no jQuery solution allows you to specify the placeholder/replacement html as a string within the element that will be replaced.
EG HTML:
<div data-placeholder="<div class='Google'><input type='text' value='abc'/></div>"></div>
<div data-placeholder="<div class='Boogle'><input type='text' value='def'/></div>"></div>
<div data-placeholder="<div class='Ooogle'><label>with label <input type='text' value='ghi'/></label></div>"></div>
<span data-placeholder="<em>Post JS</em>">Pre JS</span>
<br />
<button id="test">click me</button>
JS:
Use querySelectorAll to select all elements with the attribute 'data-placeholder' (returns a NodeList)
var placeholders = document.querySelectorAll('[data-placeholder]'); //or by ids, classnames, element type etc
Extend the NodeList prototype with a simple 'each' method that allows us to iterate over the list.
NodeList.prototype.each = function(func) {
for (var i = 0; i < this.length; i++) {
func(this[i]);
}
return this;//return self to maintain chainability
};
Extend the Object prototype with a 'replaceWith' method that replaces the element with a new one created from a html string:
Object.prototype.replaceWith = function(htmlString) {
var temp = document.createElement('div');//create a temporary element
temp.innerHTML = htmlString;//set its innerHTML to htmlString
var newChild = temp.childNodes[0];//(or temp.firstChild) get the inner nodes
this.parentNode.replaceChild(newChild, this);//replace old node with new
return this;//return self to maintain chainability
};
Put it all together:
placeholders.each(function(self){
self.replaceWith(self.dataset.placeholder);//the 'data-placeholder' string
});
Another example but here we only replace one specific element with some hard-coded html on click:
document.getElementById("test").addEventListener('click', function() {
this.replaceWith("<strong>i was a button before</strong>");
}, false);
DEMO: http://jsfiddle.net/sjbnn68e/
use the code below :
var x = document.createElement('placeholder');
x.innerHTML = "example";
document.body.appendChild(x);