C
C
Cheizer2018-02-05 16:13:21
JavaScript
Cheizer, 2018-02-05 16:13:21

How to access DOM elements of the document tree from a function?

Friends, I'm completely dumb, it seems, I can't figure out how to select elements from a function that is connected by a file. It seems like a simple task and everyone does it, I can’t do it, what’s wrong?

Here is an example document

here is a document

<!DOCTYPE html>
<html lang="ru">
<head>
    <title>Заголовок</title>
</head>
<body>

<div class="wrapper">
<h1>Заголовок</h1>
<a href="#" class="order-btn">кнопка</a>
</div>

<script>
$(document).on('click','.order-btn',function(){
addParam();
});     
</script>

<script type="text/javascript" src="/main.js"></script>
</body>
</html>


here is the function that is included at the end of the document in the main.js file

function addParam() {
var datatitle = $(this).parent().find('h1').text();
alert(datatitle);
}


And alert does not display anything, how to get elements from a function?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
tyzberd, 2018-02-05
@Cheizer

the function has its own this
https://jsfiddle.net/zdz3mvvf/1/

G
Gleb Starkov, 2018-02-05
@colonel

$('.order-btn').on('click', function(){
    // code here
});

and it is desirable to include main.js above this code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question