Can't compare two strings in JavaScript [duplicate] - javascript

This question already has answers here:
Which equals operator (== vs ===) should be used in JavaScript comparisons?
(48 answers)
Closed 6 years ago.
I have the following function, which should return different values based on the head's text:
function getPage(){
var page;
var headText = $.trim($('h1').text());
if(headText=="Page 1"){
page= 'a';
}else if(headText=="Page 2"){
page= 'b';
}else if(headText=="Page 3"){
page ='c';
}else if(headText=="Page 4"){
page= 'd';
}else{
page= 'ERROR';
}
return page;
}
Unfortunately, the function only returns "ERROR". I've tried it without the trim method. I've tried it by writing Page 1 - Page 4 into variables of their own and comparing 2 variables in the if() section. Nothing works. Where is my error?
(I am certain that the text of the < h1>- Element is "Page 1", "Page 2", "Page 3" or "Page 4")

First, console.log(headText); to see what you're actually getting.
You may be getting the text of the h1's children added onto the text of the h1 - see http://api.jquery.com/text/, specifically
Get the combined text contents of each element in the set of matched elements, including their descendants. [emphasis mine]
If that's the case, see this question and answer for a solution.

Your code works fine if there is only one h1 tag on your page. If there are multiple h1 tags then their text will be concatenated in headText.
You should uniquely identify your h1 tag with an id attribute to get only that tag's text.

Related

If statement on for a phrase rather then a specific title? [duplicate]

This question already has answers here:
How to check whether a string contains a substring in JavaScript?
(3 answers)
Closed 2 years ago.
I'm currently working on a cms that will have an alert appear on multiple pages. I am currently using an if statement to have the alert appear only a page with a specific page title. Is there a way of generalizing it and having it appear on all articles with the word "Test" in the title?
At the moment my logic is if #pageTitle === "Test Article Two display....
I tried doing #pageTitle === "Test" but that only shows on the article that has the title Test rather then other titles with the word Test in them.
Here is my code :
<script>
if(document.title === "Test Article Two") {
document.body.classList.add("show-alert");
}
</script>
Methods -
Regex, case sensitive:
if (/Test/.test(document.title)) { ... }
Regex, case insensitive
if (/test/i.test(document.title)) { ... }
indexOf, case sensitive, (fastest)
if (document.title.indexOf("Test") !== -1) { ... }
includes (ES6), case sensitive
if (document.title.includes("Test")) { ... }
You can use the JavaScript string method includes: if (document.title.includes('Test')).

Create a Tampermonkey script [duplicate]

This question already has answers here:
How to change the name field of an <input> in an AJAX-driven page?
(1 answer)
How to change a browsed page's <input>?
(1 answer)
Closed 4 years ago.
I want to create a Tampermoney script that writes something in an input field, if it finds a string on the page. E.g:
If the page contain the string "life is", the script should automatically append "good".
(I want to make this with word detection, so the string "life is", will appear on the page after that the page was accessed)
First you need to get the body as String and the input you want to modify
<input id='input-id' />
const page = document.body.innerHTML
const input = document.getElementById('input-id')
Then check if the value you want is in the page
if(page.search('life is') !== -1)
input.value = 'life is good'

Simplest way to escape all special chars of user input text [duplicate]

This question already has answers here:
Sanitizing user input before adding it to the DOM in Javascript
(7 answers)
Closed 5 years ago.
I am adding a option to a select that is input by a user:
function prependToSelect(userInput){
$('#x').prepend('<option>' + userInput + '</option>');
}
what is the safest and most simple way to make sure there is nothing dangerous in userInput that can break the javascript or html? It would also be good if the solution/function would be reusable in different scenarios.
My inital answer would be to create a options element and set the innerText instead of innerHTML
but since u use jQuery...
$('#x').prepend($('<option>', {text: userInput}))
Don't add it as HTML.
document.querySelector("#x")
.appendChild(document.createElement("option"))
.textContent = userInput;
This adds it as .textContent so no HTML will be parsed, so no danger.

Show more than 10,000 characters in a JavaScript Alert [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript object max size limit at 10000 chars
I want to check whether html source contains a specified string, but I'm only getting 10,000 characters (in alert box)
var str=document.documentElement.innerHTML;
if(str.indexOf("abcxyz") !== -1)
{
alert(str);
}
How can I fix that?
If you need to display a huge string in alert boxes, I guess you could split it into 10,000-character chunks and display them in order. Alternatively, just use console.log to print it out.
And is there a better way to detect a "onClick" event?
Better than what? JavaScript events will bubble up to the top containing element (unless some element in the chain calls stopPropagation()), so an easy way to detect click events would be to attach a click handler to document.body:
document.body.onclick = function() { alert('Click!'); }

Determine type of an element in Javascript [duplicate]

This question already has answers here:
How to get the name of an element with Javascript?
(5 answers)
Closed 9 years ago.
I have this code:
var parent = links[i].parentNode;
I'd like to write something like:
if (parent.typeOfElement == "div") {
...
}
How can I do that?
You can use .tagName, which is (for elements) the same as .nodeName.
So:
if (parent.tagName === "DIV") {
//
}
Note that the tag name is supposed to be returned in uppercase for HTML, but in XML (including xhtml) it is supposed to preserve the original case - which for xhtml means it should be lowercase. To be safe, and allow for any future changes to your document type and allow for non-standard browser behaviour you might want to convert to all upper or all lower:
if (parent.tagName.toUpperCase() === "DIV") {
//
}
In my experience .tagName is used much more often, but I gather that some consider .nodeName a better choice because it works for attributes (and more) as well as elements.
if (parent.nodeName == "div") {
...
}
See: http://www.javascriptkit.com/domref/elementproperties.shtml

Categories

Resources